5

I have function which needs to be run on click event. However it is working fine with onclick attribute of anchor tag but not working with HREF attribute. It is giving id undefined. Here is demo code

HTML

<a href="javascript:test(this)" id="first">click</a>

JS

function test(obj){
alert(obj.id)
}
4

5 回答 5

3

this在那种情况下是window,而不是控制。将 javascript 放置在 中hrefonclick. 这是一个小提琴

于 2013-09-20T18:55:25.400 回答
3

这是一个修复:

<a href="#" onclick="javascript:test(this);" id="first">click</a>
于 2013-09-20T18:56:37.593 回答
2

这个问题已经得到了答案,但如果你想使用你在问题中使用的函数,那么你应该像这样使用它

HTML:

<a href="http://heera.it" onclick="return test(this.id)" id="first">click</a>

JS:

function test(obj){
    alert(obj);
    return false; // this is required to stop navigation to that link
}

请注意,return false如果您在href此示例中具有价值,那么您应该使用,但出于这个原因,return false还有其他选项,例如event.preventDefault()or 。event.returnValue = false (for IE)

演示。另一个演示(没有return false)。在 MDN 上阅读有关此关键字的信息。

于 2013-09-20T19:09:55.330 回答
0

我喜欢Matt Kruse 的 Javascript Best Practices文章。在其中,他指出使用该href部分执行JavaScript代码是一个坏主意。

以下是在锚点上调用 javascript 的一些好的做法:

<a href="javascript:;" onClick="return DoSomething();">link</a>
<a href="javascript:void(0);" onClick="return DoSomething();">link</a>
<a href="#" onClick="return DoSomething();">link</a>
于 2013-09-20T18:54:11.820 回答
0

使用锚标记的 onclick 事件。href 内部的 this 表示当前窗口。

于 2013-09-20T18:58:37.863 回答