我有一个点击事件,我试图获取最外层父div的索引,但似乎无法返回它。
以下是几个div的列表:
<div class="owl-item">
<div class="icon-holder-selection" id="sel11">
<div class="thumbnail" id="cur11">
<img src="images/icons/11.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="11"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
<div class="owl-item">
<div class="icon-holder-selection" id="sel12">
<div class="thumbnail" id="cur12">
<img src="images/icons/12.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="12"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
<div class="owl-item">
<div class="icon-holder-selection" id="sel13">
<div class="thumbnail" id="cur13">
<img src="images/icons/13.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="13"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
我的点击事件如下所示:
$(document).on("click", ".remove-selection", function(e) {
e.preventDefault ();
//var index = $(this).index();
var parent = $(this).closest('div');
var index = $(".owl-item").index(parent);
console.log("INDEX: " + index);
});
知道我错过了什么吗?
答案 0 :(得分:2)
您需要为.owl-item
中的div提供一个类名.closest()
,否则它只会返回您span
元素的直接父级。
工作演示:http://jsfiddle.net/1t6xgbth/
$(document).on("click", ".remove-selection", function(e) {
e.preventDefault ();
//var index = $(this).index();
var parent = $(this).closest('div.owl-item');
var index = $(".owl-item").index(parent);
alert(index);
console.log("INDEX: " + index);
});
答案 1 :(得分:1)
使用owl-item选择器代替文档,使用delegateTarget更简单,更简单:
$('.owl-item').on("click", ".remove-selection", function(e) {
e.preventDefault ();
console.log($(e.delegateTarget).index());
});