将“this”传递给onclick事件

53

可能是重复问题:
如何将当前元素作为事件函数的参数?

这种方法可行吗?

<script type="text/javascript">
var foo = function(param)
{
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

不要使用这个,而是使用那个?

<script type="text/javascript">
var foo = function()
{
    document.getElementId("bar").innerHTML = "Not a button";
};
</script>
<button onclick="foo()" id="bar">Button</button>

第一种方法是否可以让我从其他地方加载JavaScript来对任何页面元素执行操作?


3
询问某事是否“会”奏效并没有太大意义。更好的做法是测试你自己,并澄清你想要使用哪些指令,以及你对它们是否不确定。 - hakre
回答:是的。 - LuckyLuke Skywalker
4个回答

55

你所拥有的代码可以工作,但是它是从全局上下文执行的,这意味着this指向全局对象。

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

你还可以使用非内联的替代方法,它附加到特定元素上下文并从该上下文执行,这使你可以通过this访问该元素。

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

23

你可以以不同的方式调用函数:foo.call(this); 这样你就能在函数内部使用 this 上下文。

示例:

<button onclick="foo.call(this)" id="bar">Button</button>​

var foo = function()
{
    this.innerHTML = "Not a button";
};

太好了!这有什么缺点吗? - Arnis Juraga

6

第一种方法适用于任何从其他地方调用的元素,因为它总是使用目标元素,而不管其id是什么。

查看这个fiddle

http://jsfiddle.net/8cvBM/


4
在JavaScript中,this总是指向我们正在执行的函数的“所有者”,或者说是一个函数作为方法的对象。当我们在页面中定义我们忠实的函数doSomething()时,它的所有者是该页面,或者说是JavaScript的窗口对象(或全局对象)。 “this”关键字是如何工作的?

this is the object from which the function is called at call-time. There is no notion of "owner" in javascript. If the function is called without the use of an object, then this is the global object (window in a browser). For instance: function f(){ console.log(this); }; o={a:f}; o.a(); var b = o.a; b(); - Pierre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接