search

Home  >  Q&A  >  body text

javascript - The difference between writing ask() directly and calling it when clicking on onclick event

window.onload=init;
function init(){
    var x=document.getElementsByTagName('a');
    for(var i in x){
        x[i].onclick=function(){
            return confirm('are you sure?');
        }
    }
}

Can be run successfully

But writing it in the following form cannot run correctly. return false is not captured. When cancel is clicked, the link still jumps. Why is this?

The functions are as follows:

window.onload=init;
function init(){
    var x=document.getElementsByTagName('a');
    for(var i in x){
        x[i].onclick=function(){
        ask();
        }
    }
}
function ask(){
    return confirm('are you sure?');
}

can be run correctly if written in the following form:

window.onload=init;
function init(){
    var x=document.getElementsByTagName('a');
    for(var i in x){
        x[i].onclick=ask;
    }
}
function ask(){
    return confirm('are you sure?');
}

Please tell me the difference between the three writing methods

世界只因有你世界只因有你2780 days ago550

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-05-19 10:33:06

    First of all, the subject of the question must know confirm('are you sure?')确定会返回true,点返回会返回false;

    Then let me say that there is no substantial difference between the three ways of writing, they just change the return value:
    1. You know
    2. ask() is changed to return ask();
    3. The best way of writing among the three

    Also

    • See the questioner is studying event binding. If you want to bind events to a bunch of regular elements, such as list li, the best way is 事件委托:

    <ul id="ul">
      <li>aaaaaaaa</li>
      <li>bbbbbbbb</li>
      <li>cccccccc</li>
    </ul>
    window.onload = function(){
      var oUl = document.getElementById("ul");
      var aLi = oUl.getElementsByTagName("li");
    
      for(var i=0; i<aLi.length; i++){
        aLi[i].onmouseover = function(){
          this.style.background = "red";
        }
        aLi[i].onmouseout = function(){
          this.style.background = "";
        }
      }
    }
    • Once you understand the event mechanism of js, capturing and bubbling, you will be almost there.

    • Final compatibility with IE: attachEvent, standard: addEventListener

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:33:06

    The second option is that you have no return

    window.onload=init;
    function init(){
        var x=document.getElementsByTagName('a');
        for(var i in x){
            x[i].onclick=function(){
            return ask();
            }
        }
    }
    function ask(){
        return confirm('are you sure?');
    }

    reply
    0
  • Cancelreply