简体   繁体   中英

Javascript return false and event.target

Could someone explain why the clicking on button1 doesn't get captured? I know return false on event click will stop the propagation, but it should still capture the element by document.addEventListener('click', function(e) {console.log(e.target);}); because we are trying to capture directly the main element via e.target not its parent element.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").click(function(){ return false; }); }); </script> </head> <body> <button id="button1">Button1 (dont get captured)</button> <button id="button2">Button2 (get captured)</button> <script> document.addEventListener('click', function(e) { console.log(e.target);}); </script> </body> </html> 

I can't change that jQuery code $("#button1").click(function(){return false}); , but still, want to capture the button1 element when it gets clicked (with javascript), is there any workaround?

i could bind another event handler to button1 like this document.getElementById("button1").addEventListener("click", function(e){console.log(e.target)}); in real there are many many elements which I want to capture (with different classes and id), it would be impractical to add an event listener to each of them, I showed one button just for an example. , I just simply want to log whichever element is clicked.

I can't change the jQuery code or HTML of the page, i want to run some tests in chrome console only, for which i want to capture each element which is clicked

thanks

The return false; prevents the browser from performing the default action for button1 link.

The equivalent code for return false is:

$('.button1')
   .click(function (event) {
       event.preventDefault();
       event.stopPropagation();
});

If you just want to stop propagation use stopPropagation() .

Take a look at this , and read more about preventDefault() and stopPropagation()

Not very efficient but worked for me

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").click(function(){ return false; }); }); </script> </head> <body> <button id="button1">Button1 (dont get captured)</button> <button id="button2">Button2 (get captured)</button> <script> elements = document.querySelectorAll('body *'); elements.forEach(function(elem) { elem.addEventListener('click', function(e){ console.log(e.target); // or simply console.log(elem) }); }); </script> </body> </html> 

Thanks to everyone, especially @mplungjan who gave me this idea

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