JavaScript'返回false'是否与HTML一起内联?

San*_*Lee 0 javascript event-handling javascript-events

我知道JavaScript return false意味着防止默认事件(如preventDefault()方法).

#1

<a href="http://stackoverflow.com" onclick="return false;">click</a>
Run Code Online (Sandbox Code Playgroud)

#2

<a id="a" href="http://stackoverflow.com">click</a>
<script>
document.getElementById('a').addEventListener('click', function(){  return false; }, false);
</script>
Run Code Online (Sandbox Code Playgroud)

我想知道为什么只有#1阻止默认事件而不是#2.我犯了一些错误吗?

编辑:对不起,我错过了锚标记的id和#2中代码的第三个参数.我添加了它,但它仍然无法正常工作.

T.J*_*der 6

第二个例子有两个问题:

  1. 你正在使用,document.getElementById但你给的是一个标记名.你可以使用document.getElementsByTagName(它返回一个NodeList你会索引的),或者给元素一个id属性并用getElementById它来查找它.

  2. 你的addEventListener电话缺少第三个参数,这是必需的.所以:

    document.getElementById('someId').addEventListener(
        'click',
        function(){  return false; },
        false // <=== Third argument, you almost certainly want `false`
    );
    
    Run Code Online (Sandbox Code Playgroud)

关于您的问题return false:如果您正在使用支持的浏览器addEventListener并且您正在使用它连接事件处理程序,请不要使用return false以防止默认操作.相反,你使用event#preventDefault.(您也可以使用event#stopPropagation停止事件冒泡,但DOM0 return false不会这样做,所以这只是额外的奖励.)

document.getElementById('someId').addEventListener(
    'click',
    function(e){
        // Prevent the default action of the link
        e.preventDefault();

        // Stop the event propagating (bubbling) to the parent element
        e.stopPropagation();
    },
    false
);
Run Code Online (Sandbox Code Playgroud)

另请注意,有很多人使用IE8及更早版本,它们不支持 addEventListener(相反,它们支持Microsoft的原始attachEvent版本;但并非所有版本都支持preventDefault或者stopPropagation).


有点偏离主题:正如您所看到的,以跨浏览器方式处理事件是一件麻烦事.这是你可以通过使用像jQuery,Prototype,YUI,Closure其他任何一个体面的JavaScript库避免的许多麻烦之一.它们可以平滑浏览器差异并提供许多有用的实用程序功能,因此您可以专注于您实际尝试构建的内容(而不是担心IE7及其早期版本的版本如何getElementById).

例子:

jQuery:jQuery提供了一个return false功能(尽管它与您正在讨论的DOM0不同),并且无论底层浏览器如何处理事件,它都可以确保event#preventDefaultevent#stopPropagation工作.所以这些都与jQuery一起工作:

// Using return false (which prevents the default AND -- unlike DOM0 stuff -- stops propagation)
$('#someId').click(function() { return false; });

// Using the DOM standard event methods -- even on browsers that don't support them
$('#someId').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

原型:Prototype提供DOM标准事件方法(即使在不支持它们的浏览器上),也event#stop只是防止默认停止传播的组合:

// Using `stop` (which prevents the default and stops propagation)
$('someId').observe('click', function(e) { e.stop(); });

// Using the DOM standard event methods -- even on browsers that don't support them
$('someId').observe('click', function(e) {
    e.preventDefault();
    e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

其他库将提供类似的功能.