我尝试在选择下拉选项时启动某个功能,但我不想在HTML中使用内联JavaScript。出于某种原因,当我运行脚本时,会自动注册更改/单击。为什么呢?
JSFiddle:http://jsfiddle.net/nysteve/QHumL/22/
var time = new Date();
var timestamp = time.toString("hh:mm:ss");
//create color from time stamp and print within div
function timeToHexColor(){
var showlist = document.getElementById("board").innerHTML +=
"#" + timestamp.split(":").join("") + "<br/>";
}
//Print colors based on time interval
function Colors(interval) {
this.interval = interval;
switch (this.interval) {
case 'second':
x = setInterval(timeToHexColor,1000);
setTimeout(stopColors, 5000);
break;
case 'minute':
x = setInterval(timeToHexColor,60000);
setTimeout(stopColors, 5000);
break;
case 'hour':
x = setInterval(timeToHexColor,60000*60);
setTimeout(stopColors, 5000);
break;
case 'day':
x = setInterval(timeToHexColor,60000*1440);
setTimeout(stopColors, 5000);
break;
default:
}
}
//For demo purposes manually kill priting after 5 seconds
function stopColors() {
clearInterval(x);
}
//Activate printing by selecting an option.
function generateColors(interval){
document.getElementById("options").onclick = Colors(interval);
/*same result with onchange
I even sent the JSFiddle settings per this link:
http://bit.ly/1gev7zR*/
}
generateColors('second');
答案 0 :(得分:1)
你不能附加这样的事件监听器,它会立即调用Colors函数。
您可以将其包装在函数中,也可以使用addEventListener,
function generateColors(interval){
document.getElementById("options").onclick = function() {
Colors(interval);
}
}
第二种方法,
function generateColors(interval) {
var el = document.getElementById("options");
el.addEventListener("click", function () {
Colors(interval);
});
}