gpt4 book ai didi

javascript - 将带有 2 个参数的函数传递给 addEvent Listener 方法

转载 作者:行者123 更新时间:2023-11-30 11:39:48 25 4
gpt4 key购买 nike

我正在尝试将一个函数传递给特定按钮上的 addEventListener 方法,但问题是函数在页面加载时直接执行,而不是在有人单击按钮时执行。

我知道如何让它与匿名函数一起工作,但我需要它与特定定义的函数一起工作。

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

关于第二个版本无法工作的原因以及如何使其按预期工作的任何想法。

更新:

我的预期和重要问题:

is there any way to make changeContent(p,content) function work without wrap it with a (anonymous) function in addEventListener method ?

最佳答案

也将其包装在一个匿名函数中

btn.addEventListener("click",function() { 
changeContent(p, content)
});

any idea of the reason why second version isn't working

因为 changeContent 是中间调用,因为您正在向它传递参数(使用圆括号)。通常,您可以通过两种方式将函数传递给函数:

  1. 只有名字,例如passFunction(changeContent);
  2. 包装在一个(匿名)函数中,如上所示 passFunction(function() { changeContent( ...);} );。中间不会调用匿名函数,因为您没有向它传递参数。

can you explain this point changeContent is intermediate called

如果您将参数传递给一个函数,它就会被调用。如果您将它包装在一个(匿名)函数中,而不将参数传递给(匿名)函数,则不会调用(匿名)函数,因此也不会调用包装函数。

is there any way to make it work without wrap it with a (anonymous) function

使用.bind 函数。第一个参数是 this 的值。所以在这种情况下你需要 3 个参数:

btn.addEventListener("click",changeContent.bind(this, p, content));

有关详细信息,请参阅 docs of .bind

关于javascript - 将带有 2 个参数的函数传递给 addEvent Listener 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com