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
首先题主先要知道
confirm('are you sure?')
点确定
会返回true
,点返回
会返回false
;然后再说三种写法并没有实质上的区别,只是变着花样返回值而已:
1.你懂
2.ask() 改为 return ask();
3.三种中最好的写法
另外
看题主在研究事件绑定,如果是给一堆有规则的元素,如列表li绑定事件,最好的办法叫
事件委托
:再搞懂js的事件机制,捕获和冒泡的话,就差不多了。
最后兼容性什么的IE:attachEvent,标准:addEventListener
第二种你是没有return