“this"的jQuery第一个孩子

我正在尝试将this"从单击的范围传递给 jQuery 函数,然后该函数可以在该单击元素的第一个子元素上执行 jQuery.好像没弄好...

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. Can't seem to get it right...

<p onclick="toggleSection($(this));"><span class="redClass"></span></p>

Javascript:

Javascript:

function toggleSection(element) {
  element.toggleClass("redClass");
}

如何引用元素的 :first-child?

How do I reference the :first-child of element?

推荐答案

如果您想将选择器应用到现有 jQuery 集提供的上下文,请尝试 find() 函数:

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode 指出,您可能只想找到上下文元素的第一个 直接后代,因此 子选择器 (>).他还指出你也可以使用 children() 函数,它与 find() 非常相似,但只搜索层次结构深处的一层(即所有你需要的......):

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). 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...):

element.children(":first").toggleClass("redClass");

相关文章