简体   繁体   中英

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? In other words, is it guaranteed that in the above example the user will never be taken to www.foobar.com? If not, is there a way that I can add that behavior without adding an html onclick attribute?

如果你想保证,那么在$(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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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