这里是jQuery新手。
如果我有这个html:
<ul id="floor-selector">
<li id="floor-1">Ground Floor</li>
<li id="floor-2">Second Floor</li>
<li id="floor-3">Third Floor</li>
<li id="floor-4">Premier Floor (Premier Floor)</li>
</ul>我希望向每个click项添加一个li事件,这样我就可以获得所在元素的id。现在,我只对我所使用的索引发出警告(而且它也不起作用),但是我真的想要我所使用的项的ID,而不是我的选择器返回的数组的索引。
这是我尝试过的,但似乎不起作用,我想我可能对each()或click()有错误的理解。
$('#floor-selector li').each( function(index, node) {
node.click( function(){ alert('I am on the '+index+'th element'); } );
// but I really want to get the ID of this element
});发布于 2013-08-24 18:47:16
这应该是可行的:
$('#floor-selector li').on('click', function() {
alert('I am the '+$(this).attr('id')+' element');
});在幕后,jQuery做了一堆魔术,本质上绑定了传递给元素的函数。因此,this引用要单击的元素并将其传递给jQuery functio:$(this)将返回包装在jQuery对象中的元素。当然,您可以直接访问id on this。
https://stackoverflow.com/questions/18421916
复制相似问题