Hook into an onClick event without using the HTML property

后端 未结 3 1087
终归单人心
终归单人心 2021-01-02 17:33

I would like to keep my JavaScript and HTML code separate. To do this, I want to make sure that I never use the following syntax:



        
相关标签:
3条回答
  • 2021-01-02 17:44

    By assigning an ID to your input element, you will easily (and efficiently) be able to access it with raw javascript

    <input type="text" name="text" id="myInput" />
    

    In your separate javascript :

    var input = document.getElementById("myInput");
    
    input.onclick = function() {alert("clicked");}
    

    Obviously you would do something more useful than an alert in the onclick function...

    0 讨论(0)
  • 2021-01-02 17:48

    To work with JavaScript, first, you have to add an id to the element that you want to append an event. That is because it makes it easy to understand your code and avoids confusion when you are writing your code. So, the HTML line will look like:

    <input type="text" name="text" id="myInputType1" />
    

    There must be no more than one id per element that is unique in the whole document. Now, there are three main ways to add events:

    /* First */
    document.getElementById("myInputType1").onclick = function(){
        /*Your code goes here */
    };
    
    /* Second */
    function Func(){
        /*Your code goes here */
    }
    document.getElementById("myInputType1").onclick = Func;
    
    /* Third */
    function Func(){
        /*Your code goes here */
    }
    document.getElementById("myInputType1").addEventListener("click", Func, false);
    

    The advantage of the last one is that you can append as many "click" (or "mouseover", ...) events as you like, and removing them one by one is possible too. But it does not work with IE<9. Instead, you have to use:

    document.getElementById("myInputType1").attachEvent("onclick", Func);
    

    jQuery way:

    $("#myInputType1").click(function(){
        /*Your code goes here */
    });
    
    0 讨论(0)
  • 2021-01-02 17:50

    If you give your element and ID, you can do:

    var el = document.getElementById("text");
    el.addEventListener("click", function(/*put code here*/) {}, false);
    
    0 讨论(0)
提交回复
热议问题