Cre*_*hts 1 javascript jquery css-selectors
我在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.
});
Run Code Online (Sandbox Code Playgroud)
如果你能在这里帮助我,请提前感谢.我可能只是在做一些愚蠢的事情,但我很难意识到这是什么.
您当前的版本不起作用,因为.attr('id')只返回ID作为字符串,而不是jQuery对象.此外,.first()返回jQuery集合中的第一个项目,而不是它们的子项.
所以,你只想要:
var test = $(this).children().first();
Run Code Online (Sandbox Code Playgroud)
要么:
var test = $('>:first-child', this);
Run Code Online (Sandbox Code Playgroud)
要么:
var test = $(this).children(':first');
Run Code Online (Sandbox Code Playgroud)
或(在较新的浏览器上):
var test = $(this.firstElementChild);
Run Code Online (Sandbox Code Playgroud)
在使用Chrome 25的jsperf测试中,该.firstElementChild方法非常快,但在MSIE <9时无法使用.children().first()was the fastest portable option, and the>:first-child'方法非常非常慢.