jQuery:保留 .index() 返回每个父索引
在下面的代码中,我试图获取单击的元素的索引,如果是,则获取其父索引。问题是它还尝试返回其父级的索引...
例如:如果我单击“1”,警报将返回 0,0
这很好。 如果我点击 A2,警报将返回 0,1
(这也很好),然后返回 1,0
(父“坐标”)!!! 我想保留它以返回父数组......
<ul>
<li>1</li>
<li>2
<ul>
<li>A2</li>
<li>B2</li>
<li>C2</li>
</ul>
</li>
<li>3</li>
<li>4</li>
<li><5</li>
</ul>
$('#control ul li').click(function(e) {
e.preventDefault();
var child = $(this).index(); // Get actual li element index
var parent = $(this).parents('li').index(); // Get the later parent index
if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
var current = $.makeArray([child,parent]); // Make an array of the coordinate
alert(current);
switcher(current);
});
In the code below, I am trying to get back the index of the element clicked and if so, its parent index. The problem is that it tries to return, also, its parent's index...
By example: if I click on "1" the alert will give back 0,0
which is good.
If I click on A2, the alert will return 0,1
(which is also good) and then return 1,0
(the parent "coordinate") !!!
I want to keep it to return the parent array...
<ul>
<li>1</li>
<li>2
<ul>
<li>A2</li>
<li>B2</li>
<li>C2</li>
</ul>
</li>
<li>3</li>
<li>4</li>
<li><5</li>
</ul>
$('#control ul li').click(function(e) {
e.preventDefault();
var child = $(this).index(); // Get actual li element index
var parent = $(this).parents('li').index(); // Get the later parent index
if(parent === -1) { parent = 0; } // If it doesn't have a parent set -1 to 0
var current = $.makeArray([child,parent]); // Make an array of the coordinate
alert(current);
switcher(current);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该停止事件传播。试试这个
You should stop the event propagation. Try this