47

可能重复:
当前元素作为其事件函数参数

这行得通吗

<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 以对任何页面元素执行操作?

4

4 回答 4

46

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<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.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>
于 2012-10-10T06:07:39.570 回答
22
于 2012-10-10T06:07:02.103 回答
6

是的,第一种方法适用于从其他地方调用的任何元素,因为它总是采用目标元素,而与 id 无关。

检查这个小提琴

http://jsfiddle.net/8cvBM/

于 2012-10-10T06:06:16.500 回答
4

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.

How does the "this" keyword work?

于 2012-10-10T06:07:05.813 回答