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
function in HREF not working using 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
回答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 href
like this example, then you should use return false
but 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.
回答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 href
section to execute JavaScript
code 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>