这是一个很难写出并有很好解释的标题。
我得到了以下 html:
<div class="requestItem clearfix">
<div class="col-sm-2">Great info goes here yo.</div>
<div class="col-sm-2">Some info goes here</div>
<div class="col-sm-2">Date goes here.</div>
<div class="col-sm-1 pull-right">
<div class="buttons">
<div class="row">
<input type="button" value="Edit" class="btn dark-button tiny-button" />
<input type="button" value="Delete" class="btn dark-button tiny-button margin-top" />
</div>
</div>
</div>
<div class="row extraInfo">
<div class="col-sm-12">
some random info
</div>
</div>
</div>
使用以下 JS:
$('.requestItem').click(function () {
console.log($(this));
if ($(this).is(':input')) {
alert("input clicked"); return;
} else { $(this).children('.extraInfo').slideToggle(); }
});
应该发生什么:当我单击元素输入的按钮之一时,不应发生切换。
会发生什么:$(this) 始终是父 div,requestItem。我知道这可能是一个正常问题,因为 requestItem 包裹在按钮周围,但是,我需要知道按钮是否被单击,因为我不想切换幻灯片。
提前致谢!
帮助后:这就是我最终得到的结果: 希望它也对其他人有帮助。
$('.requestItem').click(function (e) {
if (!$(e.target).is(':input')) {
$(this).children('.extraInfo').slideToggle();
}
});
最佳答案
默认情况下,jQuery 单击处理程序中的 this
返回的是它绑定(bind)到的元素(在本例中为 .requestItem
)。要获取被单击的元素,请使用e.target
:
$('.requestItem').click(function (e) {
console.log($(e.target));
if ($(e.target).is('input')) {
alert("input clicked"); return;
} else { $(this).children('.extraInfo').slideToggle(); }
});
fiddle :http://jsfiddle.net/c6zbwq03/
关于javascript - 无法使用 onclick 获取正确的 $(this) 元素。尝试使用 :not for input inside a div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25512960/