在 on() 方法中获取处理程序



$( document ).ready(function() {
$('#handler').on('click', '.selector', function(){
alert( $(this).text());
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
handler content
<a href="#" class="selector">selector content</a>
</div>

如何在不显式指定的情况下获取on方法中的#handler

使用事件"delegateTarget"属性

$( document ).ready(function() {
$('#handler').on('click', '.selector', function(e){
console.log(e.delegateTarget);
});
});

工作示例:-

$( document ).ready(function() {
$('#handler').on('click', '.selector', function(e){
console.log(e.delegateTarget);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
handler content
<a href="#" class="selector">child</a>
<div>
<a href="#" class="selector">grand child</a>
</div>
<div>
<div>
<a href="#" class="selector">great grand child</a>
</div>
</div>
</div>

在这种特定情况下,您可以直接使用您拥有的唯一 ID

$("#handler").

如果这是一个类,你必须$(this).parent()到顶层。

你可以把它链接到第n级,直到你到达顶部。$(this).parent().parent()......

或者,由于您知道选择器,因此可以执行$(this).parents("selector")

如果父级有层次结构,则使用 closest((,

$(this).closest('div')

如果它是目标元素的直接父元素,则使用 parent((,

$(this).parent('div');

选择器是唯一的,并且具有像handler这样的id,那么最好的选择是

$('#handler')

将其更改为

$( document ).ready(function() {
$('#handler').on('click', function(){
//$(this) here will be #handler.
});  
});

或者,如果您仍然希望在有人单击.selector时触发该函数,则可以执行以下操作

$( document ).ready(function() {
$('#handler').on('click', '.selector', function(){
var handler = $(this).parent();
}); 
});

最新更新