Javascript 将“this”传递给 onclick 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12812893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing 'this' to an onclick event
提问by FatalKeystroke
Possible Duplicate:
The current element as its Event function param
可能重复:
当前元素作为其事件函数参数
Would this work
这行得通吗
<script type="text/javascript">
var foo = function(param)
{
param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>
rather than this?
而不是这个?
<script type="text/javascript">
var foo = function()
{
document.getElementId("bar").innerHTML = "Not a button";
};
</script>
<button onclick="foo()" id="bar">Button</button>
And would the first method allow me to load the javascript from elsewhere to perform actions on any page element?
第一种方法是否允许我从其他地方加载 javascript 以对任何页面元素执行操作?
回答by Konstantin Dinev
The code that you have would work, but is executed from the global context, which means that this
refers to the global object.
您拥有的代码可以工作,但从全局上下文执行,这意味着this
指向全局对象。
<script type="text/javascript">
var foo = function(param) {
param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>
You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this
.
您还可以使用非内联替代方案,该替代方案附加到特定元素上下文并从该上下文执行,从而允许您从this
.
<script type="text/javascript">
document.getElementById('bar').onclick = function() {
this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>
回答by Arkadiusz 'flies' Rzadkowolski
You can always call funciton differently: foo.call(this);
in this way you will be able to use this
context inside the function.
你总是可以以不同的foo.call(this);
方式调用this
函数:这样你就可以在函数内部使用上下文。
Example:
例子:
<button onclick="foo.call(this)" id="bar">Button</button>?
<button onclick="foo.call(this)" id="bar">Button</button>?
var foo = function()
{
this.innerHTML = "Not a button";
};
回答by Ashirvad
Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.
是的,第一种方法适用于从其他地方调用的任何元素,因为它始终采用目标元素而不管 id。
check this fiddle
检查这个小提琴
回答by Buzz
In JavaScript this
always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.
在 JavaScript 中,this
总是指我们正在执行的函数的“所有者”,或者更确切地说,是指函数作为其方法的对象。当我们在页面中定义我们忠实的函数 doSomething() 时,它的所有者是页面,或者更确切地说,是 JavaScript 的 window 对象(或全局对象)。