index() 有效吗?
$('.mybutton').on('click',function(){
console.info("button", $(this).index(), "was clicked");
});
如果元素是兄弟元素,它应该可以工作,如docs、If we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings 中所述。
检查下面的示例:
$(".button").on("click", function() {
$("#results").html("You've clicked on the element with the index " + $(this).index());
});
.button {
padding: 5px;
border: 1px solid grey;
margin: 5px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<div class="button">Example 0</div>
<div class="button">Example 1</div>
<div class="button">Example 2</div>
<div class="button">Example 3</div>
<div class="button">Example 4</div>
</div>
<div><b>Results:</b>
</div>
<div id="results"></div>
如果由于某些奇怪的原因不起作用,快速解决方案将是.....
(请注意,根据标准/性能,这可能不是最佳解决方案)
$('.mybutton').each(function(i) {
$(this).on('click',function(){
console.info("button", i, "was clicked");
});
});
但如果 index 真的不起作用,您应该将类、id、数据参数(任何允许我们区分项目的任何内容)添加到您要修改的按钮。
例如,假设您向第 5 个按钮添加一个类 special-modifier,您会执行以下操作:
$('.mybutton').on('click',function(){
if($(this).is(".special-modifier")) {
console.info("special modifier button was clicked");
}
});