假设我有这样的标记:
<ul id="wizard">
<li>Step 1</li>
<li>Step 2</li>
</ul>
我有这个jQuery:
$("#wizard li").click(function () {
// alert index of li relative to ul parent
});
单击该li
时,如何获取该子li
相对于其父get的索引
例如,当您单击“步骤1”时,应该会弹出一个带有"0“的alert
。
发布于 2011-02-15 02:48:02
$("#wizard li").click(function () {
console.log( $(this).index() );
});
然而,与其为每个列表项附加一个单击处理程序,使用delegate
会更好(性能更好),如下所示:
$("#wizard").delegate('li', 'click', function () {
console.log( $(this).index() );
});
在jQuery 1.7+中,您应该使用on
。下面的示例将事件绑定到#wizard
元素,其工作方式类似于委托事件:
$("#wizard").on("click", "li", function() {
console.log( $(this).index() );
});
发布于 2011-02-15 02:51:27
类似于:
$("ul#wizard li").click(function () {
var index = $("ul#wizard li").index(this);
alert("index is: " + index)
});
发布于 2011-02-15 02:52:32
看看这个example。
$("#wizard li").click(function () {
alert($(this).index()); // alert index of li relative to ul parent
});
https://stackoverflow.com/questions/4996002
复制相似问题