简体   繁体   中英

event.stopPropagation() Not Ending Bubbling In Javascript

I am starting to learn how this bubbling works in Javascript. Now my problem is, I guess I don't understand it completely! I am running an onclick in HTML (Which looks like this:

onclick="checkboxhit(<?php echo $allmail[$key]["mailid"]; ?>)"

), and it is running both the If and Else statements. Basically I am just trying to check WHEN and WHEN NOT check boxs are clicked. Here is the Javascript I am using:

listofmailids = [];
function checkboxhit(mailid) {
    if (listofmailids.indexOf(mailid) == -1) {
        listofmailids.push(mailid);
        $("#deletemail").css("color", "#474747");
        event.stopPropagation()
    }
    else {
        listofmailids.splice(listofmailids.indexOf(mailid), 1);
        if (listofmailids.length == -1) {
            $("#deletemail").css("color", "#A3A3A3");
        }
        event.stopPropagation()
    }
}

Yet the event.stopPropagation() is not stopping both the If and Else statements from executing. How could I fix this? Thank you!

When using onclick , if you want the event object, you need to explicitly pass it

onclick="checkboxhit(<?= json_encode($allmail[$key]['mailid']) ?>, event)"

and in your function

function checkboxhit(mailid, e) {
    e.stopPropagation();
    // etc

json_encode() will ensure the $allmail[$key]['mailid'] value is safe for use as a JavaScript literal.


If you want to stop propagation and prevent the default action, you can use a falsy return value like so

onclick="return checkboxhit(...)"

and in your function

return false;

return false is sufficient to stop bubbling as long as there is no JavaScript run-time error prior to reaching the false return.

Explicit passing the event parameter could be done in a more reliable fashion:

<a id="test">...</a>
<script>
function checkboxhit(mailid){
  return function(e){
    if (e) e.stopPropagation;
    ...
  }
}
document.getElementById('test').onclick=checkboxhit('123');
</script>

The above code runs in IE as well. The chosen answer will cause an error because "e" is not defined.

You should be using event listeners instead of inline handlers. The Event object is added automatically in that case...

Anyway, consider the following - it will behave exactly as you expect :)

<div id="outer">
  <button id="test">click me</button>
</div>

then...

document.getElementById('test').addEventListener('click', function (ev) {
  ev.stopPropagation()
}, false)

document.getElementById('outer').addEventListener('click', function (ev) {
  // never called...
}, false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM