我想在没有任何重定向的情况下运行一个简单的JavaScript函数。

把JavaScript调用放在href属性中(像这样)有什么区别或好处吗?

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

与把它放在onclick属性(绑定到onclick事件)?


当前回答

 <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>   

其他回答

最好的方法是:

<a href="#" onclick="someFunction(e)"></a>

问题是这将在浏览器中添加一个散列(#)到页面URL的末尾,从而要求用户单击返回按钮两次才能进入您的页面之前的页面。考虑到这一点,您需要添加一些代码来停止事件传播。大多数javascript工具包已经有了这个函数。例如,dojo工具包使用

dojo.stopEvent(event);

这样做

将onclick放在href中会冒犯那些坚信内容与行为/动作分离的人。争论的焦点是你的html内容应该只关注内容,而不是表现形式或行为。

现在的典型路径是使用javascript库(例如。Jquery),并使用该库创建一个事件处理程序。它看起来像这样:

$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
<a href="#" onclick="try{FUNCTION_YOU_WANT()}catch(e){}return false">click here</a>

这个也可以

<a (click)='myFunc()'>Click Here </a>

(onclick)在带有bootstrap的Angular项目中并不适用。

我用了下面这行代码:

<a id="LinkTest" title="Any Title"  href="#" onclick="Function(); return false; ">text</a>