Javascript joins onClick event

I have the following code that I know is not working correctly. Yes, I know how to do this in jQuery, but in this case I cannot use jQuery. Please do not respond to jQuery.

<form> <input type="text" name="input1" onclick="alert('hello')"> <input type="text" name="input2"> <input type="text" name="input3"> </form> <script type="text\javascript"> window.onload = function () { var currentOnClick; for (var i = 0; i < document.forms[0].elements.length; i++) { currentOnClick = document.forms[0].elements[i].onclick; document.forms[0].elements[i].onclick = function () { if (currentOnClick) { currentOnClick(); } alert("hello2"); } } } </script> 

What I'm trying to do is iterate over form elements and add to the onclick function. But due to the fact that currentOnClick is null in my last iteration, this does not work as expected. I want to save each of the elements of onclick methods and play them in the new function that I create.

What I want:

  • When the input1 button is pressed, a hi warning is issued, and then hello2

  • When the Input2 button is pressed, click "hello2"

  • When Input3 is clicked, the warning "hello2" is issued

+4
source share
2 answers

It helps:

 window.onload = function () { for (var i = 0, element; element = document.forms[0].elements[i]; i++) { element.onclick = (function (onclick) { return function(oEvent) { // reference to event to pass argument properly oEvent = oEvent || event; if (onclick) onclick(oEvent); // new code "injection" alert("hello2"); } })(element.onclick); } } 

Or that:

 window.onload = function () { for (var i = 0, element; element = document.forms[0].elements[i]; i++) { element.exonclick = element.onclick; element.onclick = function (oEvent) { if (this.exonclick) { this.exonclick(oEvent); } // alert("hello2"); } } } 

Please be careful, the technique will not work if event handlers have been added with the DOM-Events API.

+3
source

as you have, all of your elements reference the same instance of currentOnClick . every time you assign currentOnClick current element of an existing onclick function, it loses the link to the previous function. you need to create a new event handler function in a separate area for each element.

 function addClickProxy(element) { var currentOnClick = element.onclick; element.onclick = function() { if (currentOnClick) { currentOnClick(); } alert("hello2"); } } window.onload = function() { for (var i = 0; i < document.forms[0].elements.length; i++) { addClickProxy(document.forms[0].elements[i]); } } 

Thus, there are 3 different instances of currentOnClick floating around, each of which is closed from the scope of the function.

+3
source

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


All Articles