Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

html - Javascript append to onClick event

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.

<form>
  <input type="text" name="input1" onclick="alert('hello')">
  <input type="text" name="input2">
  <input type="text" name="input3">
</form>


<script type="textjavascript">
  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 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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...