我試圖通過其中有2個參數對特定按鈕的addEventListener
方法的功能,但問題是直接執行時,頁面加載,而不是執行它,當有人點擊該按鈕功能。以2個參數傳遞函數的addEvent監聽方法
我知道如何使之與匿名函數的工作,但我需要它與特定定義的函數,而不是工作。
function changeContent(elem,str){
elem.textContent = str;
}
var btn = document.querySelector("button");
var p = document.querySelector("p");
var content = "Someone Clicked the Button!";
// add event listener on click to the button
// version 1 with anonymous function worked as expected
btn.addEventListener("click",function(){
p.textContent = content;
});
// version 2 with specific defined function not working as expected
btn.addEventListener("click",changeContent(p,content));
任何想法爲什麼第二個版本不工作,以及如何使其按預期工作的原因。
更新:
我的預期和重要的問題:
有沒有什麼辦法讓
changeContent(p,content)
功能工作 沒有addEventListener
方法用(匿名)功能包嗎?
你能解釋這一點changeContent被稱爲中間更新 – Oghli
它。讓我知道,如果它不清楚! – Julian
我知道你不能將函數傳遞給另一個函數,如果它調用像'functionName(functionName(argument1,argument2))' 是正確的嗎? – Oghli