“this"的jQuery第一个孩子 [英] jQuery first child of "this"

查看:31
本文介绍了“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");

这篇关于“this"的jQuery第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆