只写一次“return false”来处理点击许多链接

only writing "return false" once to handle clicking on many links

本文关键字:处理 链接 许多 false return 一次      更新时间:2023-09-26

与其多次编写return false;,有没有办法设置链接集合,以便如果单击其中任何一个,单击功能将return false;?我仍然希望将大多数链接return true以便显示return truereturn false将不胜感激。

目标是编写更少的代码。我也想知道这是否是一个坏主意,因为我无法理解的原因。

最简单的方法是将一个事件侦听器绑定到文档,并检查目标:http://jsfiddle.net/gKZ7q/

document.addEventListener('click', function(e) {
    if (e.target.nodeName.toUpperCase() === 'A') e.preventDefault();
}, false);
  • 对于具有嵌套元素的锚点,必须添加一个额外的循环:

    var targ = e.target;
    do {
        if (targ.nodeName.toUpperCase() === 'A') {
            e.preventDefault();
            break;
        }
    } while ((targ = targ.parentNode) !== document.documentElement);
    // document.body should be fine. Using document.documentElement in case
    // that a fool places an anchor outside the <body>
    
  • 链接也可以通过密钥事件触发。