JQuery: Stop Spreading?

I added stopPropagation, however, I still get two pop-ups in a row. This is better than before when there were 20 pop-ups for the one item that was clicked .... is there a better approach or am I missing something?

$(top.document).ready(function () { $("*").click(processAction); }); function processAction(e) { var clicked = e.target; e.stopPropagation(); alert(clicked.tagName); e.stopPropagation(); switch (clicked) { case "A": //execute code block 1 break; case "INPUT": //execute code block 2 break; default: //code to be executed if n is different from case 1 and 2 } }; 
+2
source share
3 answers

I would say that definitely do not put a click handler on every element. As @Rin stated, you can assign them by tag or another selector.

If you really want to handle all the clicks on the page this way, I would suggest placing one handler on the document and letting the click events go to that.

This is much more efficient and there is no need to do e.stopPropagation() .

Example: http://jsfiddle.net/y6hry/

 $(top.document).ready(function () { // All clicks on the page will bubble up to the document // and fire the handler. $(document).click(processAction); }); function processAction(e) { var clicked = e.target; alert(clicked.tagName); switch (clicked.tagName) { case "A": //execute code block 1 break; case "INPUT": //execute code block 2 break; default: //code to be executed if n is different from case 1 and 2 } }; 
+3
source

use

 $('*').each(map, function(key, value) { $(this).click(processAction); }); 

instead

0
source

My little advice: replace * with a or input . Now your code will be simpler and you can remove the switch. (I see that in the switch you check which item was clicked).

0
source

Source: https://habr.com/ru/post/888374/


All Articles