开发者

How can I get the index of non-sibling elements in jquery?

HTML:

<u开发者_运维技巧l>
    <li>Help</li>
    <li>me</li>
    <li>Stack</li>
    <li>Overflow!</li>
</ul>

<br>

<ul>
    <li>Can</li>
    <li>I</li>
    <li>connect</li>
    <li>these?</li>
</ul>

Javascript/JQuery:

$("li").live('click', function(){

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

});

I put together a simple jsfilled page to help describe my problem: http://jsfiddle.net/T4tz4/

Currently clicking on an LI alerts the index relative to the current UL group. I'd like to know if it was possible to get a 'global index' so that clicking on "Can" returns the index value of 4.

Thank you, John


Just put the 'li' selector inside index()

$('li').live('click', function() {
    alert( $(this).index('li') );
});

Live demo: http://jsfiddle.net/T4tz4/3/


http://api.jquery.com/index/

If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector.


Here's a solution: http://jsfiddle.net/T4tz4/1/

$("li").each(function(index) {$(this).data("index",index);});

$("li").live('click', function(){

    alert($(this).data("index"));

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜