href与onclick中的JavaScript函数 [英] JavaScript function in href vs. onclick
问题描述
我想在没有任何重定向的情况下运行一个简单的JavaScript函数。
I want to run a simple JavaScript function on a click without any redirection.
将JavaScript调用放在<$ c $之间是否有任何区别或好处c> href 属性(如下所示:
Is there any difference or benefit between putting the JavaScript call in the href
attribute (like this:
<a href="javascript:my_function();window.print();">....</a>
)vs将它放入 onclick
属性(将其绑定到 onclick
事件)?
) vs. putting it in the onclick
attribute (binding it to the onclick
event)?
推荐答案
将onclick放在href中会冒犯那些坚信内容与行为/行为分离的人。争论的焦点是你的html内容应该只关注内容,而不是表现或行为。
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
这些天的典型路径是使用javascript库(例如jquery) )并使用该库创建一个事件处理程序。它看起来像:
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
这篇关于href与onclick中的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!