简体   繁体   中英

Calling JavaScript function for HTML link

I'm trying to use JQuery so that when the user clicks on an HTML link, a function that I write in the JavaScript file is called.

<a href="#" id="advanced_options">Show advanced options</a>

And

$(document).ready(function() {

  $("#advanced_options").click(function() {
    alert('hello');
  });

});

When I click on the link, it doesn't alert, but instead jump to another link. Why is that?

If you're loading the link via an ajax query, so it's not on the page during the initial loading of the page use the jQuery on function: http://api.jquery.com/on/

$(document).ready(function() {

  $(document).on( 'click' , "#advanced_options" , function(event) {
    event.preventDefault();
    alert('hello');
  });

});

You must prevent default browser behaviour:

$(document).ready(function() {

  $("#advanced_options").click(function(event) {
    event.preventDefault();
    alert('hello');
  });

});

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