【发布时间】:2013-04-10 04:27:11
【问题描述】:
我如何获取被点击的 child $(this) 元素的 parent 元素相对于 document 的索引值?
HTML
<html>
<body>
<header>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
</header>
<section>
<section>
<article>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
</article>
</section>
</section>
</body>
</html>
在此 HTML 中,可以在正文中您喜欢的任何位置声明画廊。所以我需要一个“智能”选择器来解决这个问题。
伪 JavaScript
$('.controls button').click(function() {
var hope = $(this).parents('.gallery').index();
alert(hope);
}
预期输出
场景
单击此文档中第二个库的按钮:
1
【问题讨论】:
-
为什么你的 HTML 没有结束标签?
-
我认为它会更容易阅读。
-
没有结束标签不容易阅读,你应该包括它们。
-
你能做一个小提琴吗?
-
@MohammadAdil 我创建了一个working fiddle。
标签: javascript jquery gallery selector indexing