for example, how to detect the index of the li elem in it's parent ul?
views:
48answers:
2
+5
A:
<ul>
<li>this</li>
<li>is</li>
<li>ul</li>
</ul>
<ul>
<li>this</li>
<li>is</li>
<li>another</li>
<li>ul</li>
</ul>
if you have something like above, you could do jQuery as:
$(function(){
$('li').click(function(){ alert('the index is '+$(this).index()) })
})
this will alert the index of the li element based on its parent ul
more on index() here.
Reigel
2010-04-22 10:02:02
i don't know this method of jQuery, thanks~
lovespring
2010-04-22 13:38:57
+1
A:
In non-IE browsers, whitespace between elements are considered text nodes (which is not the case in IE), which affects the index of subsequent elements. To give the same results in all browsers, the function below by default filters out whitespace nodes, and has an optional parameter to include them if that's what you want:
function indexOfNode(node, includeWhitespace) {
var index = 0, n = node;
while ( (n = n.previousSibling) ) {
if (includeWhitespace || n.nodeType != 3 || !/^\s*$/.test(n.data)) {
++index;
}
}
return index;
}
Tim Down
2010-04-22 11:00:18