简体   繁体   中英

Click-Event firing immediatly

I am registering a click event for a button which then should execute a function in which I register a click event for the whole page body.

function test_method() {
    document.body.addEventListener(
        "click",
        function do_stuff() {
            alert("test");
        },
        false
    );
}

document.getElementById("btn_new_function").addEventListener("click", test_method, false);

What I'm trying to do here is to catch a click event anywhere on the page, but only after it was created by clicking the button before. What is happening instead is that the click event for the body fires immediatly when I click the button. It makes sense in that the button is in the body too, yeah, but the event wasn't even created when the click happened, so why does it trigger?

https://jsfiddle.net/1fj0vkzr/

How can I prevent this? I only want to register the click event for the body, not have it execute immediatly.

Add stopPropagation not to bubble up immediate event:

function test_method(e) {
    e.stopPropagation();
    document.body.addEventListener(
        "click",
        function do_stuff() {
            alert("test");
        },
        false
    );
}

Also your implementation potentially will add listeners on every click on a button. So there will be multiple handlers created on body click.

Update

stopImmediatePropagation matches better here ( https://developer.mozilla.org/ru/docs/Web/API/Event/stopImmediatePropagation )

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