Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

onclick 事件点击将ask()直接写入和调用的区别

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

可以直接运行成功

但是将其写成以下形式不能正确运行,return false 没有被捕获,当点击取消时,链接仍然跳转 ,这是为什么?

函数如下:

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?');
}

写成如下形式可以正确运行:

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?');
}

求教三种写法的区别


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

1 Answer

0 votes
by (71.8m points)

首先题主先要知道 confirm('are you sure?')确定会返回true,点返回会返回false;

然后再说三种写法并没有实质上的区别,只是变着花样返回值而已:
1.你懂
2.ask() 改为 return ask();
3.三种中最好的写法

另外

  • 看题主在研究事件绑定,如果是给一堆有规则的元素,如列表li绑定事件,最好的办法叫事件委托:

<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 = "";
    }
  }
}
  • 再搞懂js的事件机制,捕获和冒泡的话,就差不多了。

  • 最后兼容性什么的IE:attachEvent,标准:addEventListener


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...