Javascript获取调用函数的dom元素

cla*_*amp 8 javascript

HTML部分:

<a href="#" onclick="callme();return false;">foo</a>
Run Code Online (Sandbox Code Playgroud)

JS部分:

function callme() {
  var me = ?; //someway to get the dom element of the a-tag
  $(me).toggle();
}
Run Code Online (Sandbox Code Playgroud)

在JS部分我可以以某种方式获得调用此函数的a-tag?

我知道我可以将它作为参数传递,但是这个函数在页面上使用了很多次,我想避免将参数放在任何地方.

谢谢!

use*_*654 12

由于您使用的是onclick属性(BAD!),您必须将其传递给函数.

onclick="callme(this); return false;"
Run Code Online (Sandbox Code Playgroud)

和js:

function callme(el) {
  var $me = $(el);
  $me.doSomething();
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用.call()设置函数的上下文.

onclick="callme.call(this,event)"
Run Code Online (Sandbox Code Playgroud)

和js

function callme(event) {
    event.preventDefault();
    $(this).doSomething();
}
Run Code Online (Sandbox Code Playgroud)

  • +2用于使用`.call()`; -1表示onclick属性不好.;) (3认同)
  • 您假设 OP 将使用 jQuery,他仅将其标记为 javascript。 (2认同)