我试图将“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)

其他回答

我刚刚写了一个插件,如果可能的话使用.firstElementChild,并在必要时返回到迭代每个单独的节点:

(function ($) {
    var useElementChild = ('firstElementChild' in document.createElement('div'));

    $.fn.firstChild = function () {
        return this.map(function() {
            if (useElementChild) {
                return this.firstElementChild;
            } else {
                var node = this.firstChild;
                while (node) {
                    if (node.type === 1) {
                        break;
                    }
                    node = node.nextSibling;
                }
                return node;
            }
        });
    };
})(jQuery);

它没有纯DOM解决方案那么快,但在Chrome 24下的jsperf测试中,它比任何其他基于jQuery选择器的方法快几个数量级。

你可以使用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/

element.children().first();

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

这可以用一个简单的魔术来完成,就像这样:

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

参考:http://www.snoopcode.com/jquery/jquery-first-child-selector