javascript - 函数为什么只执行了一次?
本文介绍了javascript - 函数为什么只执行了一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
通过 addeventListener() 添加的函数只执行了一次?
···
box1.addEventListener('mouseover',test(2));
function test(i){
console.log(i);
}
···
为什么一打开网页控制台就输出 2 并且再次将鼠标悬停在上面的时候并不会输出 2
如果代码这样写:
···
box1.addEventListener('mouseover',test);
function test(){
console.log(2);
}
···
一打开网页并不会直接输出 2 而是当鼠标悬停在该盒子上才输出,并且每次悬停都会输入一个 2,在这里 test(i) 和 test 有什么区别?
解决方案
这样写是否可以帮助理解?
var test = function(i) {
console.log(i);
};
var result = test(2);//result其实是undefined
box1.addEventListener('mouseover', result);//每次mouseover都尝试调用一个undefined?说白了,有个屌用!
而第二种是:
var test = function() {
console.log(1);
};
box1.addEventListener('mouseover', test);//test是函数本身嘛,于是就有了每次mouseover都调用test函数的结果
补充:
想传递参数怎么办?
方法一
玩个闭包?
var test = function(i) {
return function() {
console.log(i);
};
};
box1.addEventListener('mouseover', test(2));//每次mouseover都会输出2
使用bind方法(不推荐)
var test = function(i) {
console.log(i);
};
box1.addEventListener('mouseover', test.bind(null, 4));//每次mouseover都会输出4
这篇关于javascript - 函数为什么只执行了一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文