How to properly use javascript-links for users wit

2019-09-08 06:14发布

问题:

I hope I'm not creating a duplicate here, but I just don't really know what to look for/didn't find anything useful yet.

I got several links (<a>) on my page that trigger the jquery click() handler, which will load a new page into a div without reload. To make those links available to non-javascript users, I want to link them to the same page (that's why I'm using s and not just any div/span/button). Propblem with that is that the script will reload anyway, so you can say jaavascript is overwritten.

So how do I prevent the browser using the link as a link with javascript? Or what's the correct solution to allow non-javascript users to be able to use the site properly as well ?

The only solution I could come up with by myself is just using buttons, but I find that quite bulky as I have to use a form although I only submit 1 variable via GET which is only specified in the link itself. Thanks for help :)

回答1:

For what you're doing, returning false will work as others have answered, but beware of overusing return false; in jQuery event handlers.

You would probably be better served by calling preventDefault() to stop the click action only. It will prevent the link from being followed, but not stop any other handlers that may be attached. See jQuery events: stop misusing return false for a detailed explanation.

example:

$("a").click(function(event) {
    // your custom code
    event.preventDefault();
});


回答2:

If you return false to the click event handler, it will not follow through with the default action, which in your case would be to follow the link to the new page...

$('a').click(function(e) {
    // process your event...
    return false;
});

Then, if javascript is disabled, it will follow the <a> tag to the new href as expected.



回答3:

Since you say you're using jQuery, return false in the event handler.

$("a").click(function() {
    // ...
    return false;
});


回答4:

jQuery gives you several ways to deal with this problem.

$('.some-link').click(function(event) {
   //just prevent browsers default behavior
   event.preventDefault();
   //stop calling all other handlers, including live
   event.stopPropagation();
   //stop calling all handlers listening to the same dom node
   event.stopImmediatePropagation()

   //do all of the above
   return false;
)}

Hope that helps.



回答5:

$( "a" ).click( function() {
    // ...
    return false;
});

This will prevent the event (ie the click) from changing the page but it will also prevent you from chaining methods. Method chaining looks like this:

$( "a" ).click( function(){} ).css( 'color', 'red' );

The click will be cancelled but the css ALSO won't execute.

Using .preventDefault() is pretty standard and won't cause this issue.

$( "a" ).click( function( event ) {
    // ...
    event.preventDefault();
});