当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to bind a .click() event only the container?

问题描述:

I want the user entry to open up accordion-style, but a .click() event is triggered even if I click on any other element inside the red box - the text, the image, etc.

I'd like to only have the "outer" whitespace cause the event to trigger.

How do I accomplish this?

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

网友答案:

You can check the target property of the event to see if it was the #box element directly by using is():

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

Updated fiddle

网友答案:
<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>
网友答案:

Just check the e.target.id to see if it matches the specific id of the outer box you want. Example below:

$('#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>
网友答案:

If you want to add the event to the parent container you will have to stop the propagation on all the child elements that will not need a click event .

Example :

since #box has the click and box is your container

you will need to give image an id and stop the propagation

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

e.stopPropagation();

})

With the example above when you click the image nothing will happen , but if you click the red container then your event will log.

网友答案:

The best way is to prevent the event if the click is done on child:

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

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

});
分享给朋友:
您可能感兴趣的文章:
随机阅读: