我想在没有任何重定向的情况下运行一个简单的JavaScript函数。
把JavaScript调用放在href属性中(像这样)有什么区别或好处吗?
<a href="javascript:my_function();window.print();">....</a>
与把它放在onclick属性(绑定到onclick事件)?
我想在没有任何重定向的情况下运行一个简单的JavaScript函数。
把JavaScript调用放在href属性中(像这样)有什么区别或好处吗?
<a href="javascript:my_function();window.print();">....</a>
与把它放在onclick属性(绑定到onclick事件)?
当前回答
这是
<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>
其他回答
<hr>
<h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
<button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
<div class="pull-right">
<button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
});
</script>
首先,将url放在href中是最好的,因为它允许用户复制链接,在另一个选项卡中打开等等。
在某些情况下(例如HTML频繁变化的网站),每次更新都绑定链接是不实际的。
典型绑定方法
正常的链接:
<a href="https://www.google.com/">Google<a/>
JS的代码是这样的:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
这种方法的好处是清晰地分离标记和行为,并且不必在每个链接中重复函数调用。
不绑定方法
然而,如果你不想每次都绑定,你可以使用onclick并传入元素和事件,例如:
<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>
这是JS的:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
这种方法的好处是你可以随时加载新链接(例如通过AJAX),而不必担心每次都要绑定。
编辑警告:请参阅评论,在这个答案中使用“nohref”是不正确的。
我使用
Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>
虽然绕了很长一段路,但还是完成了任务。使用A风格来简化 然后就变成:
<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style>
<a nohref onClick="alert('Hello World')">HERE</a>
将onclick放在href中会冒犯那些坚信内容与行为/动作分离的人。争论的焦点是你的html内容应该只关注内容,而不是表现形式或行为。
现在的典型路径是使用javascript库(例如。Jquery),并使用该库创建一个事件处理程序。它看起来像这样:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
就我个人而言,我觉得把javascript调用放在HREF标签中很烦人。我通常不太注意某些东西是不是javascript链接,而且经常想在一个新窗口中打开东西。当我尝试这样做与这些类型的链接之一,我得到一个空白页面上什么都没有和javascript在我的位置栏。但是,通过使用onlick可以避免这一点。