简体   繁体   中英

jQuery click on anchor tag reloads page

As many other threads and external forums suggest, I've tried placing e.preventDefault() (while passing e as parameter, not in code sample) in every place imaginable, but it doesn't prevent the anchor from reloading the page. When I step through the debugger, it will assign every div with scrollNav the click event, but when I click on the div-link it just reloads the page and the debugger does not stop on any lines in the highlightSelection function. Another method I've tried is to use an anonymous function inside this.click and place e.preventDefault() as the first line, but it does nothing.

I also don't really understand why you would want to place e.preventDefault() as so many others have suggested. Isn't it basically saying return false? That may stop a link from reloading the page, but won't it prevent the code in the method from executing?

jQuery(document).ready(function() {

jQuery('.scrollNav').each(initSideNavForSelection);

}); // end ready

function initSideNavForSelection() {
    this.click(highlightSelection);
}

function highlightSelection() {
    var selectedDataID = this.attr("data-id");

jQuery('.scrollNav').each(function() {
    if (this.attr("data-id") === selectedDataID) {
        this.addClass("selected");
    } else {
        this.removeClass("selected");
    }
})

}

Add onclick="return false;" to the anchor. OR change initSideNavForSelection function to

this.click(function(e) {
    e.preventDefaults();
    highlightSelection();
});

either works

There are a few things I had to do to get your codes to run. You can take a link at this fiddle here .

Here's the list:

  1. Add JQuery as the framework to be used for your fiddle, under the Frameworks & Extensions section on the top left corner.
  2. Remove the broken onclick="Event.stop(event)" inlined attribute as Event is undefined.
  3. Replace the usage of this with $(this) in both your initSideNavForSelection() and highlightSelection() functions. this represents a DOM object and $(this) is a JQuery wrapper around this . The latter will respond to JQuery methods like .click() , but not the former.

So far, there is no page reload in your fiddle, with or without e.preventDefault() .

Finally, in addition to event.preventDefault() , return false also calls event.stopProgagation() to prevent the event from bubbling up the DOM, before terminating the callback execution immediately. A call to event.preventDefault() doesn't terminate the function call immediately.

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