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
6 Answers
Reset to default 6Either 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
版权声明:本文标题:javascript - Getting the index of a parent element of an event target - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741689361a2392630.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论