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

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

Javascript:

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

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


当前回答

你可以使用DOM

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

其他回答

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

    $(element).first();

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

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

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

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

然后使用下面的代码

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

你试过了吗

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

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

我添加了jsperf测试,以查看不同方法获取第一个子节点的速度差异(总共1000多个子节点)

给定,notif = $('#foo')

jQuery方法:

$(":first-child", notif) - 4,304 ops/sec -最快 notify .children(":first") - 653 ops/sec -慢85% notify .children()[0] - 1416 ops/sec -慢67%

本地方法:

JavaScript原生' ele。firstChild - 4,934,323 ops/sec(所有上述方法都比firstChild慢100%) 原生DOM ele来自jquery: notif[0]。firstChild - 4,913,658 ops/秒

因此,不建议使用前3种jQuery方法,至少对于第一个孩子是这样(我怀疑其他孩子也会这样)。如果你有一个jQuery对象,需要获取第一个子元素,那么从jQuery对象中获取原生DOM元素,使用数组引用[0](推荐)或.get(0)并使用ele.firstChild。这将得到与常规JavaScript使用相同的结果。

所有测试都在Chrome Canary build v15.0.854.0中完成

你可以使用DOM

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