... and...">

How to change the click handler of this image?

I have the following HTML:

<img src='img.png' onclick='document.write("Hi there!")' /> 

... and the following JavaScript:

 $(document).ready(function() { // Change the click handler $('img').click(function() { alert("Hi there!"); }); }); 

I expect the click handler for the image to be replaced, and when I click on it, a warning dialog will appear. Instead, the content of the page changes as dictated by the click handler in the tag.

How to change the click handler at runtime?

Note: Here is an interactive demo you can play with:
http://jsfiddle.net/ykmaG/

+4
source share
2 answers

You need to delete the original onclick :

 $('img').removeAttr('onclick').click(function() { ... }); 
+8
source

I would not use the onclick attribute, but use jQuery click () instead.

To untie an event, see Undo () .

Does it help at all?

0
source

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


All Articles