【问题标题】:In the click event Jquery how is $(this)?在点击事件 Jquery 中 $(this) 怎么样?
【发布时间】:2018-03-06 13:01:53
【问题描述】:

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

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


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

$(this)#parent 还是 #child

【问题讨论】:

  • 如果您没有找到相关文档,您就不能自己测试一下吗?只需输入 console.log(this);在您的活动中。

标签: javascript jquery events this


【解决方案1】:

是孩子,你怎么不试试

$('#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>

【讨论】:

    【解决方案2】:

    上下文this 与事件目标相关。你的情况是#child

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

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

    【讨论】:

    • 在我的情况下,#child 在某些函数之后被添加到厄运中;)
    【解决方案3】:

    这称为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>

    【讨论】:

      【解决方案4】:

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

      $(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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        相关资源
        最近更新 更多