简体   繁体   中英

How to catch link or button click?

How do I catch all links and button pressed? Without having to add my JavaScript method to every link and button?

Anytime my browser wanrs to redirect to page1.aspx stop it from redirecting and have mt browser click a link found on the page to page2.aspx instead!

            $(document).ready(function(){
              $("a,:button").click(function(){
               alert("Link or button clicked!");
              });
            });

I think "Babiker's" solution is better than "Bears will eat you" because it calls the event handler only when link of button is clicked whereas in the other case, it calls for all the click events on the page and checks if the element clicked was a link or button.

Babiker's solution is more optimized.

Note, this wont work for any elements added in future.

You might wanna try this.

$("a, button").live("click", function(){ ... });
"<script type=""text/javascript"" src=""http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js""></script>  

<script type=""text/javascript""> 
    $(document).ready(function(){
        $('body').click(function() {
           // do something here
        //alert(""Link or button clicked!"");
        });
    });
</script>"

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