我正在尝试将“this”从点击的跨度传递给jQuery函数,然后jQuery函数可以在该clicked元素的第一个子元素上执行jQuery。似乎没能做对......
<p onclick="toggleSection($(this));"><span class="redClass"></span></p>
使用Javascript:
function toggleSection(element) {
element.toggleClass("redClass");
}
如何引用元素的第一个子元素?
答案 0 :(得分:454)
如果要将选择器应用于现有jQuery集提供的上下文,请尝试find() function:
element.find(">:first-child").toggleClass("redClass");
JørnSchou-Rode指出,您可能只想找到上下文元素的第一个直接后代,因此the child selector(&gt;)。 He also points out您也可以使用children() function,这与find()非常相似,但只搜索层次结构中的一个级别(这就是您所需要的......):
element.children(":first").toggleClass("redClass");
答案 1 :(得分:69)
将children
function与:first
selector一起使用,以获取单 element
的第一个孩子:
element.children(":first").toggleClass("redClass");
答案 2 :(得分:49)
我已添加jsperf测试,以查看获得第一个孩子的不同方法的速度差异(总共1000多个孩子)
给出,notif = $('#foo')
jQuery方式:
$(":first-child", notif)
- 4,304 ops / sec - 最快notif.children(":first")
- 653 ops / sec - 85%慢notif.children()[0]
- 1,416 ops / sec - 67%较慢原生方式:
ele.firstChild
- 4,934,323 操作/秒(以上所有方法与{{1}相比都慢100%)firstChild
- 4,913,658 ops / sec 所以,不建议使用前3个jQuery方法,至少对于第一个孩子来说(我怀疑其他许多情况也是如此)。如果你有一个jQuery对象并且需要获得第一个孩子,那么从jQuery对象获取本机DOM元素,使用数组引用notif[0].firstChild
(推荐)或[0]
并使用.get(0)
。这提供了与常规JavaScript使用相同的结果。
所有测试均在Chrome Canary build v15.0.854.0中完成
答案 3 :(得分:9)
你试过吗
$(":first-child", element).toggleClass("redClass");
我认为您希望将元素设置为搜索的上下文。可能有一种更好的方法可以做到这一点,其他一些jQuery大师会跳到这里然后扔给你:)
答案 4 :(得分:4)
我刚刚编写了一个插件,如果可能的话会使用.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);
它不如纯DOM解决方案快,但在Chrome 24下的jsperf tests中,它比任何其他基于jQuery选择器的方法快几个数量级。
答案 5 :(得分:2)
这可以通过这样一个简单的魔术来完成:
$(":first-child", element).toggleClass("redClass");
参考:http://www.snoopcode.com/jquery/jquery-first-child-selector
答案 6 :(得分:2)
你可以使用DOM
$(this).children().first()
// is equivalent to
$(this.firstChild)
答案 7 :(得分:1)
请像这样使用它 首先给一个类名称来标记p,如“myp”
然后使用以下代码
$(document).ready(function() {
$(".myp").click(function() {
$(this).children(":first").toggleClass("classname"); // this will access the span.
})
})
答案 8 :(得分:-3)
如果你想要第一个孩子,你需要
$(element).first();
如果您想从元素中获取dom中的特定第一个元素,请使用下面的
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");