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
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
事件委托
: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