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

前端 未结 8 1296
滥情空心
滥情空心 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 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:

    Here is some text Click!
    ​ $("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/

提交回复
热议问题