admin管理员组

文章数量:1302342

With this code provided:

$("#myList").on("click", "span", function (event) {
    alert($(this).index());
});

And HTML:

<ul id="myList">
    <li>item 0 <span>span 0</span></li>
    <li>item 1 <span>span 1</span></li>
    <li>item 2 <span>span 2</span></li>
    <li>item 3 <span>span 3</span></li>
</ul>

If you click on any of the <span> elements, "0" will always be alerted. I think this is because there is only one <span> within each <li>, so it will always be given the index of 0.

What I want it to do, is return the index of the <span>'s parent - in this case, it will be the index of the parent <li> within <ul id="myList">. For example, clicking on <span>span 2</span> will alert "2".

JSFiddle

With this code provided:

$("#myList").on("click", "span", function (event) {
    alert($(this).index());
});

And HTML:

<ul id="myList">
    <li>item 0 <span>span 0</span></li>
    <li>item 1 <span>span 1</span></li>
    <li>item 2 <span>span 2</span></li>
    <li>item 3 <span>span 3</span></li>
</ul>

If you click on any of the <span> elements, "0" will always be alerted. I think this is because there is only one <span> within each <li>, so it will always be given the index of 0.

What I want it to do, is return the index of the <span>'s parent - in this case, it will be the index of the parent <li> within <ul id="myList">. For example, clicking on <span>span 2</span> will alert "2".

JSFiddle

Share edited Jun 13, 2015 at 6:47 royhowie 11.2k14 gold badges53 silver badges67 bronze badges asked Jun 13, 2015 at 6:14 user2121620user2121620 67612 silver badges28 bronze badges 1
  • 4 Why does this have upvotes? Lol, it's a pretty basic question. Whatever, not my judgement to make... walks off into the shadows – user3117575 Commented Jun 13, 2015 at 6:32
Add a ment  | 

6 Answers 6

Reset to default 6

Either use $(this).parent().index() or $(this).closest('li').index().

The latter will alert the index of the li even if you decide to put a new element into your spans and bind the event to that.

Do just that:

alert($(this).parent().index());

Use $.fn.parent method:

$("#myList").on("click", "span", function (event) {
    alert($(this).parent().index());
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myList">
    <li>item 0 <span>span 0</span></li>
    <li>item 1 <span>span 1</span></li>
    <li>item 2 <span>span 2</span></li>
</ul>

check fiddle

JS:

alert($(this).parent().index());

USE parent().

console.log($(this).parent().index());

Check out the jQuery DOCS

Here is a possible solution: https://jsfiddle/9naxotz1/2/

$("#myList").on("click", "span", function (event) {
    alert($(this).parent().index());
});

本文标签: javascriptGetting the index of a parent element of an event targetStack Overflow