Javascript:如何让Control在方法中发送自己

Pro*_*ool 28 javascript onclick

<a href="" id="someId" onclick="SomeMethod(self);"></a>
Run Code Online (Sandbox Code Playgroud)

SomeMethod可能有的地方:

function SomeMethod(item)
{
  item.setAttribute('name', item.id);
}
Run Code Online (Sandbox Code Playgroud)

代替:

function SomeMethod(itemId)
{
  var someItem;

  someItem = document.getElementById(itemId);
  someItem .setAttribute('name', someItem .id);

}
Run Code Online (Sandbox Code Playgroud)

愚蠢的例子,但想法不是发送id本身,而是实际控制调用方法.我发誓这可以做,但没有运气搜索...部分是因为我甚至不确定要搜索什么.

我认为这是自我,但当我运行的剧本时,自我似乎不是我想要的.

Qui*_*son 41

使用this关键字.

<a href="" id="someId" onclick="SomeMethod(this);"></a>
Run Code Online (Sandbox Code Playgroud)

  • 我知道这很简单.有点肮脏的问,但哦. (6认同)

Jam*_*sky 11

实际上,您不需要将此作为参数传递给函数,因为您有一个可以访问的click事件对象.所以:

<a href="" id="someId" onclick="clickEventHandler()"></a>
<script>
function clickEventHandler(event) {

    if (!event) {
        event = window.event; // Older versions of IE use 
                              // a global reference 
                              // and not an argument.
    };

    var el = (event.target || event.srcElement); // DOM uses 'target';
                                                 // older versions of 
                                                 // IE use 'srcElement'
    el.setAttribute('name', el.id);

}
</script>
Run Code Online (Sandbox Code Playgroud)


Ant*_*nes 7

我倾向于在HTML属性的所有函数调用中使用这种方法: -

onclick="SomeMethod.call(this)"
Run Code Online (Sandbox Code Playgroud)

然后在javascript中执行: -

function SomeMethod()
{
   this.setAttribute('name', this.id);
}
Run Code Online (Sandbox Code Playgroud)

当您还可以在Javascript代码中直接分配给事件处理程序属性时,这具有明显的优势: -

document.getElementById("someID").onclick = SomeMethod
Run Code Online (Sandbox Code Playgroud)

如果SomeMethod将context元素作为参数,那么设置起来会非常尴尬: -

function(id) {
   var elem = document.getElementById(id)
   elem.onclick = function() { SomeMethod(elem); }
}("someID");
Run Code Online (Sandbox Code Playgroud)

更糟糕的是,这将是内存泄漏关闭.