我有這個設置,只是爲了找到一個元素的index(),但它應該用相同的nodename來查看同一級別的元素。jquery find index()相同的節點名稱
返回的數字不符合預期。請參閱代碼評論。我想filteredByNodeNameIndex爲'2'。
希望這個例子的代碼是足夠清晰:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>TestDrive</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" >
function TestDrive()
{
var $obj = $("#div2");
console.log("$obj.length:" + $obj.length); // returns: 1
var $filtered = $obj.parent().children($obj[0].nodeName); // find all divs in same parent
console.log("$filtered.length:" + $filtered.length); // returns: 3
var $obj_clone = $filtered.find($obj); // find original element again. Is something wrong here?
console.log("$objAgain.length:" + $obj_clone.length); // returns: 0
var filteredByNodeNameIndex = $obj_clone.index(); // i want the number 2 here
console.log("filteredByNodeNameIndex:" + filteredByNodeNameIndex); // returns: -1
}
</script>
</head>
<body onload="new TestDrive()">
<div id="container">
<!-- some random elements just for test -->
<a></a>
<div id='div1'></div>
<div id='div2'></div>
<span></span>
<span></span>
<a></a>
<div></div>
<a></a>
</div>
</body>
</html>
誰能那個地方,這是錯的?
什麼是不工作?數字出錯了,代碼被炸燬了嗎? –
這些數字與預期不符。請參閱代碼評論。我想filteredByNodeNameIndex爲'2'。 var filteredByNodeNameIndex = $ obj_clone.index(); //我想要數字2在這裏 –