【问题标题】:how to select my first child in jQuery [duplicate]如何在 jQuery 中选择我的第一个孩子 [重复]
【发布时间】:2013-01-29 03:49:30
【问题描述】:

我在选择 jQuery 中的第一个孩子时遇到了一些麻烦。我试图这样做是为了避免有很多 if 语句。基本上,您单击一个按钮。此类选择器设置为处理我的 JS 中的点击。进入 JS 后,我想获取刚刚单击的项目的子项,但我没有任何乐趣。

这是我的 JS 中的内容:

$('.itemClicked').click(function(){

var id = $(this).attr('id').first();
    // it can't find the method first() here. If I just find the id, I get the 
    // correct ID of what I just clicked.          

var test = id.first();
    // I tried the above to seperate the ID from the first() method request
    // no joy with this either.

test.toggleClass("icon-tick");
    // this is my ultimate aim, to toggle this icon-tick class on the item
    // clicked.

});

如果您能在这里帮助我,请提前致谢。我可能只是在做一些愚蠢的事情,但我很难意识到那是什么。

【问题讨论】:

    标签: javascript jquery css-selectors


    【解决方案1】:

    您当前的版本不起作用,因为.attr('id') 只是将 ID 作为字符串返回,而不是 jQuery 对象。此外,.first() 返回 jQuery 集合中的第一项,而不是它们的子项。

    所以,你只想:

    var test = $(this).children().first();
    

    或:

    var test = $('>:first-child', this);
    

    或:

    var test = $(this).children(':first');
    

    或(在较新的浏览器上):

    var test = $(this.firstElementChild);
    

    在使用 Chrome 25 的 jsperf 测试中,.firstElementChild 方法非常快,但在 MSIE .children().first()was the fastest portable option, and the>:first-child' 方法非常,很慢。

    【讨论】:

    • 要明确(因为Javascript中没有“ID”之类的概念),他的代码试图在字符串上调用first()方法,attr()会返回什么。
    • @mori57 谢谢 - 澄清
    【解决方案2】:

    也许

    $('.itemClicked').click(function(){
        $(':first-child',this).toggleClass('icon-tick');
    });
    

    是你所追求的。

    现场示例:http://jsfiddle.net/ySMLG/

    【讨论】:

    • 我总是忘记你可以像这样作用域选择器。 +1 提醒。 :)
    • 如果 click 元素下面有多个元素,则此代码不起作用,因为 $(sel, this) 相当于 .find()not 相当于 .children()
    【解决方案3】:

    如果您只想在被点击的项目上切换“icon-tick”类,那么这将起作用:

    $('.itemClick').click(function () {
        $(this).toggleClass('icon-tick');
    });
    

    声明:

    $(this).attr('id').first()
    

    不起作用,因为 attr() 方法返回属性的值,而不是 jQuery 对象,因此它不可链接。

    【讨论】:

    • OP 明确表示他们希望在点击的项目的第一个子项上切换类
    • 不,实际上,OP 代码中的注释指出“这是我的最终目标,在单击的项目上切换此图标刻度类。”尽管如此,这个问题并不完全清楚,所以我在回答前加上“如果...”
    • @JamesTracy 但每个人都知道 cmets 在添加到代码后的 5 秒内就会过时...
    猜你喜欢
    • 2012-08-16
    • 2023-03-16
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 2020-02-15
    • 2022-06-28
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多