即使没有进行任何更改,也会进行更改/单击触发

时间:2013-10-05 20:47:11

标签: javascript function onclick onchange

我尝试在选择下拉选项时启动某个功能,但我不想在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');

1 个答案:

答案 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);
    });
}

Updated DEMO