本文翻译自:jQuery first child of “this”
I'm trying to pass "this" from a clicked span to a jQuery function that can then execute jQuery on that clicked element's first child. 我试图将“this”从点击的跨度传递给jQuery函数,然后jQuery函数可以在该被点击元素的第一个子元素上执行jQuery。 Can't seem to get it right... 似乎无法做对......
<p onclick="toggleSection($(this));"><span class="redClass"></span></p>
Javascript: 使用Javascript:
function toggleSection(element) {
element.toggleClass("redClass");
}
How do I reference the :first-child of element? 我如何引用元素的第一个子元素?
#1楼
参考:https://stackoom.com/question/9Y0s/jQuery第一个孩子-这个
#2楼
If you want immediate first child you need 如果你想要第一个孩子,你需要
$(element).first();
If you want particular first element in the dom from your element then use below 如果您想从元素中获取dom中的特定第一个元素,请在下面使用
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");
try out : http://jsfiddle.net/vgGbc/2/ 尝试: http : //jsfiddle.net/vgGbc/2/
#3楼
I've just written a plugin which uses .firstElementChild
if possible, and falls back to iterating over each individual node if necessary: 我刚刚编写了一个插件,如果可能的话使用.firstElementChild
,并在必要时回退到迭代每个单独的节点:
(function ($) {
var useElementChild = ('firstElementChild' in document.createElement('div'));
$.fn.firstChild = function () {
return this.map(function() {
if (useElementChild) {
return this.firstElementChild;
} else {
var node = this.firstChild;
while (node) {
if (node.type === 1) {
break;
}
node = node.nextSibling;
}
return node;
}
});
};
})(jQuery);
It's not as fast as a pure DOM solution, but in jsperf tests under Chrome 24 it was a couple of orders of magnitude faster than any other jQuery selector-based method. 它没有纯DOM解决方案那么快,但在Chrome 24下的jsperf测试中 ,它比任何其他基于jQuery选择器的方法快几个数量级。
#4楼
If you want to apply a selector to the context provided by an existing jQuery set, try the find() function : 如果要将选择器应用于现有jQuery集提供的上下文,请尝试使用find()函数 :
element.find(">:first-child").toggleClass("redClass");
Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). JørnSchou-Rode指出,您可能只想找到context元素的第一个直接后代 ,因此是子选择器 (>)。 He also points out that you could just as well use the children() function , which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...): 他还指出你也可以使用children()函数 ,它与find()非常相似,但只搜索层次结构中的一个深层(这就是你需要的......):
element.children(":first").toggleClass("redClass");
#5楼
Have you tried 你有没有尝试过
$(":first-child", element).toggleClass("redClass");
I think you want to set your element as a context for your search. 我想你想把你的元素设置为搜索的上下文。 There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :) 可能有更好的方法来做到这一点,其他一些jQuery大师将跳进这里扔掉你:)
#6楼
使用children
功能与:first
选择得到的单个第一子element
:
element.children(":first").toggleClass("redClass");