以下是我的javascript:
我的要求是我需要使事件可配置(逗号分隔),如可配置间隔。我该怎么做.Plz建议。
喜欢var events_list = mousedown,mousemove,scroll
var interval = 7000;
function Init () {
if (document.addEventListener) {
document.addEventListener ("mousedown", function () {ChangeState ()}, false);
document.addEventListener ("mouseup", function () {ChangeState ()}, false);
document.addEventListener ("mousemove", function () {ChangeState ()}, false);
document.addEventListener ("keydown", function () { ChangeState ()}, false);
document.addEventListener ("scroll", function () {ChangeState ()}, false);
}
}
setInterval(function(){
myFunction();},interval);
}
答案 0 :(得分:1)
你想要什么是不可能的:
var events_list = mousedown,mousemove,scroll
在您的mousedown示例中,mousemove和scroll将被视为变量,并且会因为未声明它们而引发错误。您可以将它们配置为逗号分隔的字符串中的元素列表:
var events_list = "mousedown,mousemove,scroll";
然后将它们分成一个数组并循环遍历它:
function Init () {
var events_list = "mousedown,mousemove,scroll";
if (document.addEventListener) {
events_list.split(',').forEach(function (eventName) {
document.addEventListener(eventName, function () {
ChangeState();
}, false);
});
}
}