简体   繁体   English

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

[英]function in HREF not working using javascript

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. 但是它可以正常使用锚标记的onclick属性,但不能使用HREF属性。 It is giving id undefined. 它给id未定义。 Here is demo code 这是演示代码

HTML HTML

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

JS JS

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

this in that context is the window , not the control. this在这方面是window ,而不是控制。 Placing javascript in the href is not the same as an event handler like onclick . 将javascript放在href中与onclick类的事件处理程序不同。 Here's a fiddle . 这是一个小提琴

这是一个修复:

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

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. DEMO。 Another DEMO (without return false ). 另一个DEMO (没有return false )。 Read about this keyword on MDN. 阅读关于这个的MDN关键字。

I enjoyed Matt Kruse's Javascript Best Practices article. 我很喜欢Matt Kruse的Javascript Best Practices文章。 In it, he states that using the href section to execute JavaScript code is a bad idea. 在其中,他声明使用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>

Use onclick event of the anchor tag. 使用锚标记的onclick事件。 this inside href represents current window. 内部href表示当前窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM