Onclick and jquery event binding, causing pain

I have a link that has an onclick attribute, and there is a switch event that I associate with the link (I know that I commit a sin here by mixing the two, but I can do nothing about it.)

Now, against this background, I have 2 scenarios:
1. The user clicks on the link. The order of events: - onclick first, and then the event of switching through jQuery
2. Fire the click event through jQuery. The execution order is different here, the related event is fired first and then onclick .

Something is going horribly wrong due to these two scenarios and a flip of order. I need related events to fire earlier than onclick . Is there a better way to do this than to remove the onclick attribute in init and store them in a link via .data() and then handle through the switch event?

One more thing I need to take care of (life is complicated), the link can be switched through the chain. those. if the user comes from another page via another link, there will be a querystring parameter with the link identifier, which is read by another javascript function, which has the script 2 mentioned above.

So, if onclick deletion should be removed, it should be done in init.

What can I do to unravel this mess?

+4
source share
1 answer

What's wrong with removing the .onclick function and re-linking it after (after you've linked all of your methods, which should fire earlier)?

HTML

 <div id="foo" onclick="inline();">click me</div> 

Javascript

 function inline() { alert('I was bound through onclick='); } $(function() { var $foo = $('#foo'), stored = $foo[0].onclick; $foo[0].onclick = null; $foo.bind('click', function() { alert('I was bound via jQuery'); }); $foo.bind('click', stored); }); 

After this code, the notification order will be as follows:

 'I was bound via jQuery' 'I was bound through onclick=' 

Demo : http://jsfiddle.net/3MKWR/

+5
source

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


All Articles