“[removed]void(0);” vs “return false” vs “preventDefault()”

前端 未结 8 1229
滥情空心
滥情空心 2020-11-28 19:44

When I want some link to not do anything but only respond to javascript actions what\'s the best way to avoid the link scrolling to the top edge of the page ?
I know sev

相关标签:
8条回答
  • 2020-11-28 19:59

    Binding:

    • javascript: URLs are a horror to be avoided at all times;
    • inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing;
    • binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS.

    Responses:

    • In jQuery return false means both preventDefault and stopPropagation, so the meaning is different if you care about parent elements receiving the event notification;
    • jQuery is hiding it here but preventDefault/stopPropagation have to be spelled differently in IE usually (returnValue/cancelBubble).

    However:

    • You have a link that isn't a link. It doesn't link anywhere; it's an action. <a> isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.
    • For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsid and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash on document load to open that element, so the link becomes useful in other contexts.
    • Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button"> or <button type="button">. You can style it with CSS to look like a link instead of a button if want.
    • However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span> instead. You can add a tabindex property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).
    • Another possibility is <input type="image">. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.
    0 讨论(0)
  • 2020-11-28 19:59

    event.preventDefault() and return false; are one thing - they instruct the browser not to process the default action for the event (in this case, navigating to the href of the anchor tag that was clicked). href=javascript: and its ilk are something else - they're causing the default action to be 'do nothing'.

    It's a question of style. Do you want to do all your work in the onclick, or do you want to be able to put actions in both the onclick and the href and rely on the capabilities of the browser to modulate between the two?

    0 讨论(0)
  • 2020-11-28 20:02

    Dreamweaver uses a nice little trick by default that I've started using.

    <a href='javascript:;'></a>
    

    It's small, it doesn't trip and anchors and it's library agnostic.

    0 讨论(0)
  • 2020-11-28 20:10

    I tend to prefer using return false, as that gives the option to give the user a choice whether to continue that action, such as shown here, in quirksmode:

    http://www.quirksmode.org/js/events_early.html#default

    It's simple, it's old, but it works well, cross-browser, regardless of the version of javascript.

    0 讨论(0)
  • 2020-11-28 20:12

    The only advantage that I can think of to using javascript:void(0) is that it will be supported even by the oldest browsers. That said, I would use one of the other unobtrusive approaches you have mentioned:

    • For most uses, event.preventDefault() and return false can be used interchangeably.
    • event.preventDefault() will prevent the page from reloading, as desired, but will allow the click event to bubble up to the parent. If you want to stop the bubbling, you can use it in conjunction with event.stopPropagation.
    • return false will additionally stop the event from bubbling up to the parent.

    I say 'interchangeably' in the first point above because much of the time we do not care whether or not an event bubbles up to the parent(s). However, when do we need some fine-tuning, we should consider points two and three.

    Consider the following example:

    <div>Here is some text <a href="www.google.com">Click!</a></div>​
    
    $("a").click(function(e) {
        e.preventDefault();
    });
    
    $("div").click(function() {
        $(this).css("border", "1px solid red");
    });
    ​
    

    Clicking on the anchor will prevent the default action of the event from being triggered, so the browser will not redirect to www.google.com. However, the event will still 'bubble up' and cause the div's click event to fire, which will add a border around it. Add e.stopPropagation() or just return false and the div's click event will not fire. You can mess with it here: http://jsfiddle.net/cMKsN/1/

    0 讨论(0)
  • 2020-11-28 20:12

    I think that I have seen as well javascript:; around as the web develops, is hard to keep track to the tricks that are available out there.. but this is mainly about accessability (besides javascript:void(0); ) and just a small correction is not javascript:void(0) but javascript:void(0); which means do nothing so pretty much as return false; although not sure if javascript:return false; does the same..

    I always use and would suggest to use javascript:void(0); for a couple of reasons.. in my humble opinion, of course.

    1.) I use it because of the same someone mentioned above.. href="#" is not appropriate as it might indicate going to the top and even in that case '#top' would be more adequate for that case. But also this can trigger something else in your code that makes use of # (hashes) so another reason is to avoid conflicts with other javascript that might be using #. And I tend to look for this when using a plugin for example, and replace them immediately.. href='#' to href='javascript:void(0);' or href='javascript:;'

    2.) If I want to re-use a function for a group of specific Anchor tags, I can call it with the selector on any attribute without worrying about detecting the click event and preventing the default action and I do it without even thinking of it as a development preference.

    3.) In most cases if you are doing link building using javascript:void(0); tries to make a link to not be followed as the old href= rel=nofollow so it avoid indexing links that are actions. I'm not so sure about this one merely because I heard that crawlers and robots can now read even Flash so would not be surprised if they can read javascript links

    4.) Referring from 2.) you can target on a class like and forget about preventing the click event default action by using a href="javascript:void(0);" and then targetting the class directly from the selector at the jQuery function.

            jQuery(function($)
            {
                //from the rel
                $('a[rel="-your-rel-id"]') ... off('click').on('click',function()
    
                //from the class
                $('a.-the-class') ... off('click').on('click',function()
    
                //from the id
    
                $('a#-the-id').off('click').on('click',function()
                {
                --do something with this link
            });
    
    }); 
    

    I rather feel more comfortable using the class as you can always do...

    $(a#-your-id).hasClass(-yourclass-)

    or any other interesting combination and affect many links.. so I really won't suggest to use the A as a selector solely..

    Normally what I see in here being suggested is this:

      jQuery(function($)
            {
                //from the rel
                $('a[rel="-your-rel-id"]').on('click',function(event)
                //do something
                //prevent the click as is passed to the function as an event
                event.preventDefault();
            });
    
    });
    
    0 讨论(0)
提交回复
热议问题