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

标签 javascript html

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

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/

相关文章:

javascript - 用于检测和替换 undefined object 属性的全局函数/服务 | Angular 2-TS

javascript - 使用javascript将td宽度更改为百分比

javascript - 为什么 HTML 页面的类为 ‘javascript’ ?

javascript - 如何根据显示的 div 数量调整 div 的大小?

javascript - 有条件地显示和隐藏从数据库生成的选择输入选项?

html - 具有动态高度的垂直滚动 div

html - CSS 网格布局的严重问题

JavaScript。 <li> 元素相对于浏览器边界的绝对位置?

javascript - 如何自定义传单 map CSS

javascript - 如何结合使用 jQuery .hover() 和 Overflow