简体   繁体   English

jQuery onClick on link元素

[英]jQuery onClick on link element

Suppose I have some code like so: 假设我有一些像这样的代码:

<a href="www.foobar.com" class="special-click">
   Content here
</a>

$( ".special-click" ).click(function(event) {
  event.preventDefault();
  // Do other stuff
});

Assuming that the jQuery library is loaded, is my jQuery guaranteed to run before the page transitions? 假设加载了jQuery库,我的jQuery是否保证在页面转换之前运行? In other words, is it guaranteed that in the above example the user will never be taken to www.foobar.com? 换句话说,是否保证在上面的例子中用户永远不会被带到www.foobar.com? If not, is there a way that I can add that behavior without adding an html onclick attribute? 如果没有,是否有一种方法可以添加该行为而无需添加html onclick属性?

如果你想保证,那么在$(document).ready(function(){})中阻止这个点击事件代码;

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>

    $(document).ready(function () {

        $(".special-click").click(function (event) {
            event.preventDefault();
            alert("test")
        });

 });  
</script>
</head>
<body>

 <a href="www.foobar.com" class="special-click">
   Content here
</a>

</body>
</html>

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

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