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 に答える