0

我试图在选择下拉选项时触发一个函数,但我不想在 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');
4

1 回答 1

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

更新了演示

于 2013-10-05T20:57:05.113 回答