[英]How can I get the index of non-sibling elements in jquery?
HTML: HTML:
<ul>
<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: 使用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/ 我整理了一个简单的jsfilled页面来帮助描述我的问题: http : //jsfiddle.net/T4tz4/
Currently clicking on an LI alerts the index relative to the current UL group. 当前单击LI会警告相对于当前UL组的索引。 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. 我想知道是否有可能得到一个'全局索引',以便点击“Can”返回索引值4。
Thank you, John 谢谢你,约翰
Just put the 'li'
selector inside index()
只需将'li'
选择器放在index()
$('li').live('click', function() {
alert( $(this).index('li') );
});
Live demo: http://jsfiddle.net/T4tz4/3/ 现场演示: http : //jsfiddle.net/T4tz4/3/
http://api.jquery.com/index/ 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. 如果选择器字符串作为参数传递,则.index()返回一个整数,指示原始元素相对于选择器匹配的元素的位置。
Here's a solution: http://jsfiddle.net/T4tz4/1/ 这是一个解决方案: http : //jsfiddle.net/T4tz4/1/
$("li").each(function(index) {$(this).data("index",index);});
$("li").live('click', function(){
alert($(this).data("index"));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.