我在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.
});
如果你能在这里帮助我,请提前致谢。我可能只是在做一些愚蠢的事情,但我很难意识到这是什么。
答案 0 :(得分:8)
您当前的版本不起作用,因为.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< 9. .children()
。first()was the fastest portable option, and the
>:first-child'方法非常非常慢。
答案 1 :(得分:1)
也许
$('.itemClicked').click(function(){
$(':first-child',this).toggleClass('icon-tick');
});
是你所追求的。
答案 2 :(得分:-2)
如果您想要做的就是在点击的项目上切换“icon-tick”类,那么这将有效:
$('.itemClick').click(function () {
$(this).toggleClass('icon-tick');
});
声明:
$(this).attr('id').first()
不起作用,因为attr()方法返回属性的值,而不是jQuery对象,因此它不可链接。