2017-10-18 104 views
0

基本問題我知道,但我無法理解的東西。我有一個模擬骰子投擲,以作爲參數臉的數量的函數:addEventListener「激活」自動

function throw(faces){ 
//My function here 
} 

然後我有按鈕,模擬不同數量的發佈會,我想他們推出throw被點擊時:

document.getElementById("4").addEventListener("click",throw(4)); 
document.getElementById("6").addEventListener("click",throw(6)); 

等等

但是,當我啓動CodePen(here),該功能自動啓動(用正確的參數雖然),然後我無法點擊的按鈕。我可以,但沒有任何反應。

我在做什麼錯?我有一種感覺,這是一個非常基本的東西,但我似乎無法得到它。我已經看到,如果你把throw而不是throw()該功能不會自動啓動,但我該如何改變參數呢?

回答

1

throw(4)執行/自動調用該方法,因爲要調用使用()功能/方法。如果你想在按鈕的事件偵聽器調用throw(4)點擊時,則使用以下命令:

document.getElementById("4").addEventListener("click", function(){ 
    throw(4); 
}); 

document.getElementById("4").addEventListener("click", throw); 
function throw(){ 
    console.log(event.target.id); //event.target.id will give the id of the element clicked 
    // your rest of the code here 
} 
0

你的throw函數需要返回一個函數到addEventListener。例如:

function throw (faces) { 
    return function() { 
     return Math.floor(Math.random() * faces); 
    } 
} 
0

您可以使用bind與預設this關鍵詞返回一個新的功能, (在這種情況下null)參數:

function throw(faces){ 
    // My function here 
} 

document.getElementById("4").addEventListener("click", throw.bind(null, 4)); 
document.getElementById("6").addEventListener("click", throw.bind(null, 6)); 

或定義一個新的函數內部它的exec utes throw

document.getElementById("4").addEventListener("click", function() { 
    throw(4); 
}); 
document.getElementById("6").addEventListener("click", function() { 
    throw(6); 
});