Ran*_*ski 3 html javascript jquery
我有以下的HTML ...
<div class="display">sometext</div>
<div class="display">sometext</div>
<div class="display">sometext</div>
Run Code Online (Sandbox Code Playgroud)
使用jQuery我希望能够点击第一个,div然后显示一条警告说你点击了第一个div,依此类推.我知道如何计算div具有特定类的s 的数量,但不知道如何判断单击哪一个.
在幕后,.index()还循环遍历所有以前的元素.以下替代方法比.index()元素具有大量兄弟节点时更有效.
$(".display").each(function(i){
$(this).click(function(){
alert("Clicked div.display, number " + i);
}
});
Run Code Online (Sandbox Code Playgroud)
我不确定'第一'这样,但你可以尝试:
$('.display').click(
function(){
alert("You clicked div number: " + ($(this).index('.display') + 1) + ", of " + $('.display').length);
});
Run Code Online (Sandbox Code Playgroud)
参考文献: