我试图将“this”从单击的span传递到一个jQuery函数,然后可以在单击的元素的第一个子元素上执行jQuery。似乎不能得到它的权利…

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

Javascript:

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

我如何引用元素的:第一个子元素?


当前回答

使用带有:first选择器的children函数来获取元素的第一个子元素:

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

其他回答

你可以使用DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)

使用带有:first选择器的children函数来获取元素的第一个子元素:

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

你试过了吗

$(":first-child", element).toggleClass("redClass");

我认为你需要将元素设置为搜索的上下文。可能有一个更好的方法来做到这一点,一些其他jQuery大师会跳在这里,扔给你:)

请像这样使用 首先,给标签p起一个类名,比如myp

然后使用下面的代码

$(document).ready(function() {
    $(".myp").click(function() {
        $(this).children(":first").toggleClass("classname"); // this will access the span.
    })
})

我在用

 $('.txt').first().css('display', 'none');