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

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

Javascript:

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

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


当前回答

我在用

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

其他回答

我在用

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

如果你想马上要第一个孩子,你需要

    $(element).first();

如果你想在你的元素的dom中指定第一个元素,那么使用下面的方法

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");

试试:http://jsfiddle.net/vgGbc/2/

element.children().first();

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

你可以使用DOM

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

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

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