簡體   English   中英

如何僅將容器綁定到.click()事件?

[英]How to bind a .click() event only the container?

我希望用戶輸入打開手風琴式,但即使我點擊紅色框內的任何其他元素 - 文本,圖像等,也會觸發.click()事件。

我只想讓“外部”空格導致事件觸發。

我該如何做到這一點?

 $('#box').click(function(e) { console.log(e); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box" style="width:80%;background:red;"> <table> <tr> <td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td> <td><b>John McDerpenstein</b></td> <td><p> A blurb goes here </p></td> </tr> </table> </div> 

小提琴

<html>
<body>
<div id="box" style="width:80%;background:red;">
  <table>
    <tr>
      <td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td>
      <td><b>John McDerpenstein</b></td>
      <td><p>
      A blurb goes here
      </p></td>
    </tr>
  </table>
</div>
<script src="jquery-1.12.3.min.js"></script>
<script>
$('img').click(function(e) {
  console.log(e);
});
</script>

</html>

您可以使用is()檢查事件的target屬性以查看它是否是#box元素:

$('#box').click(function(e) {
    if ($(this).is(e.target))
        console.log(e);
});

更新了小提琴

只需檢查e.target.id ,看它是否與您想要的外盒的特定id匹配。 示例如下:

 $('#box').click(function(e) { if (e.target.id === "box") console.log('click'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box" style="width:80%;background:red;">this is the outer box <table> <tr> <td><img src="http://i.imgur.com/NaCmGyX.jpg" style="width:50px;height:50px;border-radius:50%;"></td> <td><b>John McDerpenstein</b></td> <td><p> A blurb goes here </p></td> </tr> </table> </div> 

如果要將事件添加到父容器,則必須停止不需要單擊事件的所有子元素傳播

示例:

因為#box有點擊,而盒子就是你的容器

你需要給圖像一個id並停止傳播

$('#imageID').click(function(e){

e.stopPropagation();

})

使用上面的示例,當您單擊圖像時,不會發生任何事情,但如果您單擊紅色容器,則您的事件將記錄。

最好的方法是在對孩子進行點擊時阻止該事件:

$('#box').click(function(e) {
    if (!$(this).is(e.target)) {
        return e.preventDefault()
    }

    // code here (or nothing, href="" action)

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM