gpt4 book ai didi

javascript - 如何判断哪个按钮调用了函数?

转载 作者:行者123 更新时间:2023-12-03 11:42:11 24 4
gpt4 key购买 nike

我如何知道哪个按钮导致该函数运行?具体来说,如果我想将函数的值设置为等于按钮的值?

var foo_button = document.getElementById("foo_button");
var bar_button = document.getElementById("bar_button");
foo_button.onclick = foo_or_bar;
bar_button.onclick = foo_or_bar;

然后在稍后的函数中:

function foo_or_bar(){

//this should return the value of the button that was pressed (in this case "foo"
//or "bar"
return button_that_sent_me;

}

有没有办法可以检测到导致这种情况发生的按钮的值?

最佳答案

您可以按照@A1rPun所说使用this,或者通过window.event访问该按钮,这在您使用内联onclicks和其他不推荐的做法时也有帮助:

JS

function foo_or_bar() {
console.log(window.event.target.value);
console.log(this.value);
}

HTML

<button id="foo_button" value="foo">internals</button>

为您提供以下控制台日志:

foo
foo

关于javascript - 如何判断哪个按钮调用了函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223771/

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