如何在jQuery中选择我的第一个孩子

how to select my first child in jQuery

本文关键字:选择我 我的 第一个 孩子 选择 jQuery      更新时间:2023-09-26

在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.
});

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

当前版本不起作用,因为.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);

在Chrome25的jsperf测试中,.firstElementChild方法非常快,但在MSIE<9..children().first()was the fastest portable option, and the>:first-child方法非常非常慢。

也许

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

就是你想要的。

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

如果你只想在点击的项目上切换类"图标勾选",那么这将起作用:

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

声明:

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

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