Javascript append to onClick event

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I have the following Code which I know doesn't work correctly. Yes I know how to do this in jQuery but in this case I cannot use jQuery. Please no jQuery answers.

What I'm trying to do is iterate through the form's elements and add to the onclick function. But due to the fact that in my last iteration currentOnClick is null this does not run as expected. I want to preserve each of the elements onclick methods and play them back in the new function I'm creating.

What I want:

  • When input1 is clicked, alert "hello" then alert "hello2"

  • When Input2 is clicked, alert "hello2"

  • When Input3 is clicked, alert "hello2"

回答1:

This 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 this:

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 warned, the technique will not work if event handlers were added with DOM-Events API.



回答2:

the way you have it, your elements all refer to the same instance of currentOnClick. each time you assign currentOnClick to the current element's existing onclick function, it loses the reference to the previous function. you need to create the new event handler function in a separate scope 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 

this way, there are 3 different instances of currentOnClick floating around, each sealed from the others by the function scope.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!