2013-10-05 39 views
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'); 
+1

這是http://stackoverflow.com的副本/ questions/3249128/javascript-event-handler-arguments =>查看您的問題的答案。 – Jealie

回答

1

你不能將一個事件偵聽器那樣,調用顏色立即發揮作用。

你可以用它在功能,或者您可以使用的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

+1

仍然困惑爲什麼它立即着火;我正在使用onclick而不是單擊方法。 無論如何,使用jQuery方法作爲Jealie發佈的鏈接中提到的答案:$(「target」)。change(function(){myfunction();});對於JS還是一個新東西,但不是jQuery的答案本質上與您的本地答案做同樣的事情 - 爲現有的事件偵聽器更改創建一個匿名函數?我想jQuery保存了所有這些本地代碼。儘管謝謝你的回答! =) – brooklynsweb

+2

@brooklynsweb:'element.onclick'需要一個函數處理函數,而不是函數值。因此,'element.onclick = myfunction;'按預期工作,並且在設置時不觸發對myfunction()的調用,而是'element.onclick = myfunction();'在設置element.onclick時評估由myfunction返回的值。 – Jealie

相關問題