在我的脚本中,我有一个 jQuery onmouseover() 绑定(bind)到以 div 作为父项列出项目。 现在,当我将鼠标移到 li 项上时,我想获取该项相对于其父元素 (div) 的索引。
所以我使用
var index = $($(this).index());
获取悬停元素索引作为整数。 jquery 文档说
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
但索引 var 是一个对象。如果我尝试警告它(而不是使用 console.log 进行基本调试),对话框的内容是“[object object]”。
你能帮我吗?为什么我的代码块返回一个对象,尽管文档说它在不带参数调用时会返回一个整数?
最佳答案
您所要做的就是去掉额外的$(...)
。代码应该是这样的:
var index = $(this).index();
关于jQuery的index()函数返回对象而不是int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11496854/