我想做的是根据元素在 div 中的位置来识别元素。我已经尝试了下面的代码并且它有效,但我很好奇是否有更有效的方法来执行此操作。
HTML:
<div class="container">
<button>One</button>
<button>Two</button>
<button>Three</button>
</div>
<div class="result"></div>
JavaScript:
$('.container button').on('click', function(e) {
clickedBtn = e.target;
btnNum = 0;
$('.container button').each(function(i) {
if ($(this)[0] === clickedBtn)
btnNum = i+1;
});
$('.result').text('Clicked button #' + btnNum);
});
最佳答案
由于您正在寻找基于 sibling 的索引,您可以调用 .index()没有任何争论。
$('.container button').on('click', function(e) {
$('.result').text('Clicked button #' + $(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<button>One</button>
<button>Two</button>
<button>Three</button>
</div>
<div class="result"></div>
关于javascript - jQuery - 通过 sibling 之间的位置(索引)识别对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26751833/