Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

javascript - href与onclick中的JavaScript函数(JavaScript function in href vs. onclick)

I want to run a simple JavaScript function on a click without any redirection.

(我想在单击时运行一个简单的JavaScript函数,而无需任何重定向。)

Is there any difference or benefit between putting the JavaScript call in the href attribute (like this:

(将JavaScript调用放入href属性之间有什么区别或好处(例如:)

<a href="javascript:my_function();window.print();">....</a>

) vs. putting it in the onclick attribute (binding it to the onclick event)?

()与将其放在onclick属性中(将其绑定到onclick事件)?)

  ask by SkunkSpinner translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

bad:

(坏:)

<a id="myLink" href="javascript:MyFunction();">link text</a>

good:

(好:)

<a id="myLink" href="#" onclick="MyFunction();">link text</a>

better:

(更好:)

<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>

even better 1:

(更好的1:)

<a id="myLink" title="Click to do something"
 href="#" onclick="MyFunction();return false;">link text</a>

even better 2:

(更好的2:)

<a id="myLink" title="Click to do something"
 href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

Why better?

(为什么更好?)

because return false will prevent browser from following the link

(因为return false将阻止浏览器跟踪链接)

best:

(最好:)

Use jQuery or other similar framework to attach onclick handler by element's ID.

(使用jQuery或其他类似框架,按元素ID附加onclick处理程序。)

$('#myLink').click(function(){ MyFunction(); return false; });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...