如何确定哪个按钮调用了函数
How to determine which button called a function?
我怎么知道是哪个按钮导致该函数运行?具体来说,如果我想将函数的值设置为与按钮的值相等?
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
"this"发送与元素相关的所有信息触发事件:
<button onclick="foo_or_bar(this.id);" id="foo">Foo</button>
function foo_or_bar(id) {
button_that_sent_me = id;
}
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量