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

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

Javascript:

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

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


当前回答

element.children().first();

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

其他回答

如果你想将选择器应用到现有jQuery集提供的上下文,请尝试find()函数:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode注意到你可能只想找到context元素的第一个直接后代,因此是子选择器(>)。他还指出,你也可以使用children()函数,它与find()非常相似,但只搜索层次结构中的一个深度(这就是你所需要的…):

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

你试过了吗

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

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

我在用

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

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

我刚刚写了一个插件,如果可能的话使用.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选择器的方法快几个数量级。