HREF 中的函数无法使用 javascript 工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18923868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:41:53  来源:igfitidea点击:

function in HREF not working using javascript

javascript

提问by Carlos

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

我有需要在点击事件上运行的功能。然而,它与锚标记的 onclick 属性一起工作正常,但不能与 HREF 属性一起工作。它给出了未定义的 id。这是演示代码

HTML

HTML

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

JS

JS

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

采纳答案by canon

thisin that context is the window, not the control. Placing javascript in the hrefis not the same as an event handler like onclick. Here's a fiddle.

this在那种情况下是window,而不是控件。在 中放置 javascripthref与像onclick. 这是一个小提琴

回答by Thiago Custodio

Here's a fix:

这是一个修复:

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

回答by The Alpha

This question already got answers but if you want to use a function as you used in your question then you should use it like

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

HTML:

HTML:

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

JS:

JS:

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

notice, return false, if you have value in hreflike this example, then you should use return falsebut there are other options like event.preventDefault()or event.returnValue = false (for IE)for this reason.

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

DEMO.Another DEMO(without return false). Read about thiskeyword on MDN.

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

回答by Irfan TahirKheli

Use onclick event of the anchor tag. this inside href represents current window.

使用锚标签的 onclick 事件。这里面的 href 代表当前窗口。

回答by Ahsan Shah

I enjoyed Matt Kruse's Javascript Best Practicesarticle. In it, he states that using the hrefsection to execute JavaScriptcode is a bad idea.

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

here are some good practices to call javascript on anchor:

以下是在锚点上调用 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>