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

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

Javascript:

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

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


当前回答

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

然后使用下面的代码

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

其他回答

你可以使用DOM

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

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

然后使用下面的代码

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

我在用

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

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

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

找到所有的孩子,先下手为强。