在点击事件中,Jquery how is $(this)



我有click jquery的事件,我想知道选择器是如何点击的......

$('#parent').on('click','#child',function(){
 //....
});  

<div id="parent">
 <div id="child">
 </div>
</div>    

$(这(#parent还是#child

是孩子,你为什么不试试

$('#parent').on('click','#child',function(){
    console.log($(this));
});  

$('#parent').on('click','#child',function(){
    console.log($(this));
});
#child {
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
    <div id="child"></div>
</div>

上下文

this与事件目标相关。 在您的情况下是#child.

此外,当id可用时,您不需要事件委派,因此请按如下方式绑定该事件:

$('#child').on('click',function(){
 //....
}); 

称为Event delegation,它允许我们将单个事件侦听器附加到父元素,该侦听器将为所有与选择器匹配的后代触发,无论这些后代现在存在还是将来添加。

因此,这里的$(this)始终将单击的子元素引用为父元素,此处为#child

一个简单的动态添加元素演示:

// Attach Event
// on(events, selector, handler);
$('#container').on('click', 'a', function(event) {
  event.preventDefault();
  console.log('Anchor clicked!');
  alert('Anchor clicked!');
});
// Create elements dynamically
$('#container').append('<a href="#output">Click me!</a>');
body{font:12px Tahoma,Arial,Helvetica,sans-serif;color:#333;margin:20px}
h1{font-size:1.4em;margin-bottom:20px}
h2{font-size:1.2em}
#container{border:1px dashed #aaa;font-size:1em;padding:10px}
a{color:green}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Dynamically added link:</h2>
<div id="container"></div>

你可以写这样的东西来检查。

$(document).ready(function() {
  $('#parent').on('click','#child',function(){
    console.log("This:", $(this));
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
 Parent
 <div id="child">
   CHILD (click on it)
 </div>
</div>

最新更新