問題描述
我正在嘗試將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第一個孩子的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!