How to find out position of clicked element?

不打扰是莪最后的温柔 提交于 2020-01-06 02:56:12

问题


How do I find out, in what position a list item was clicked.

So, let's say I clicked the second list item:

<li><a href="#"><span>Tab 2</span></a></li>

Then, I would get an alert saying something like:

You clicked the second list item?

JQuery Code

$('#top-betting ul li:first').addClass('current');
$('#top-betting div:not(:first)').hide();

$('#top-betting ul li span').click(function()
{
    ...?
});

Markup

<div id="tabs">
   <ul class="clearfix">
      <li><a href="#"><span>Tab 1</span></a></li>
      <li><a href="#"><span>Tab 2</span></a></li>
      <li><a href="#"><span>Tab 3</span></a></li>
   </ul>

   <div>Content 1</div>
   <div>Content 2</div>
   <div>Content 3</div>
</div>

回答1:


You can do it using .closest() and .index() like this:

$('#top-betting ul li span').click(function() {
   var index = $(this).closest('li').index();
});

Overall, I think this is what you're after:

$('#top-betting ul li span').click(function() {
    $("#top-betting div").eq($(this).closest('li').index()).show()
                         .siblings('div').hide();
});​



回答2:


index is the method you're after.

$('li a').click(function(e){
        var $li = $(this).parents('li');
        var $ul = $(this).parents('ul');
        alert($ul.children().index($li));
    });

Check the jsFiddle: http://jsfiddle.net/9V9D2/




回答3:


You're looking for the index method.



来源:https://stackoverflow.com/questions/3159301/how-to-find-out-position-of-clicked-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!