javascript - The difference between writing ask() directly and calling it when clicking on onclick event
世界只因有你
世界只因有你 2017-05-19 10:31:06
0
2
501
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

世界只因有你
世界只因有你

reply all(2)
滿天的星座

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

習慣沉默

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?');
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!