获取元素的索引作为相对于父级的子级 [英] Get index of element as child relative to parent

查看:104
本文介绍了获取元素的索引作为相对于父级的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个标记:

<ul id="wizard">
    <li>Step 1</li>
    <li>Step 2</li>
</ul>

我有这个jQuery:

And I have this jQuery:

$("#wizard li").click(function () {
    // alert index of li relative to ul parent
});

如何获得孩子的索引 li 相对于它的父级,当点击 li

How can I get the index of the child li relative to it's parent, when clicking that li?

例如,当你点击第1步时,弹出一个带<0的警告

For example, when you click "Step 1", an alert with "0" should pop up.

推荐答案

$("#wizard li").click(function () {
    console.log( $(this).index() );
});

但是,不是为每个列表项附加一个单击处理程序,而是使用<更好(性能明智) a href =http://api.jquery.com/delegate/> 委托 ,如下所示:

However rather than attaching one click handler for each list item it is better (performance wise) to use delegate which would look like this:

$("#wizard").delegate('li', 'click', function () {
    console.log( $(this).index() );
});

在jQuery 1.7+中,你应该使用 。下面的示例将事件绑定到 #wizard 元素,就像委托事件一样:

In jQuery 1.7+, you should use on. The below example binds the event to the #wizard element, working like a delegate event:

$("#wizard").on("click", "li", function() {
    console.log( $(this).index() );
});

这篇关于获取元素的索引作为相对于父级的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆