[英]jQuery overall index from parent element with specific class
How i can use the jQuery index() method to find the index of a parent element with a certain class related to the whole document by a click on a link inside this element? 我如何使用jQuery index()方法通过单击元素内部的链接来查找与整个文档相关的某个类的父元素的索引?
The following code does not work and returns -1 and i would like to know the index of the div element with the class "navi" in the document... 以下代码不起作用,返回-1,我想知道文档中具有“ navi”类的div元素的索引...
JavaScript 的JavaScript
$('.navi').on('click', 'a.link', function(event) {
var parent = $(this).closest('.navi');
var index = $(document).index(parent);
console.log(index);
return false;
});
HTML 的HTML
<html>
...
<body>
...
<div class="navi">
...
<div class="anotherdiv">
...
<a href="#" class="link"></a>
...
</div>
...
</div>
...
<div class="navi">...</div>
...
</body>
<html/>
You need to change the selector from document to ".navi", like so: 您需要将选择器从文档更改为“ .navi”,如下所示:
var index = $('.navi').index(parent);
At the minute, you're trying to find the index of the element within the document (which is a collection of 1, in which navi doesn't exist). 此刻,您正在尝试查找文档中元素的索引(该元素是1的集合,其中navi不存在)。 What you really want to do is find where the element lives within a collection of elements with the .navi class which the above does. 您真正想要做的是使用上面的.navi类找到元素在元素集合中的位置。
Try this: 尝试这个:
$('.navi').on('click', 'a.link', function(event) {
var parent = $(this).closest('.navi');
var index = $('.navi').index(parent[0]);
console.log(index);
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.