2012-05-06 40 views
0

而不是写return false;多次,有没有办法来设置等环节的集合,如果其中任何一个被点击的点击功能会return false;?我仍然希望获得大多数链接return true,因此显示代码return truereturn false会特别感谢。只写“返回false”一旦处理点击很多链接

的目标是写更少的代码。我也想知道,如果这是一个坏主意,我不明白的理由。

回答

2

的simpliest方法结合一种事件监听到文档,并检查目标: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> 
    
  • 链接也可以通过关键事件触发。
+0

感谢,但我还是想有许多环节'回报TRUE'。你能告诉我们'if'情况会是什么样子吗?我想最简单的就是...'getElementsByClassName ==='dontGoThere',是/否? –

+1

'targ.nodeName.toUpperCase()===“A''也可以写为'/^a$/i.test((targ.nodeName)' – KooiInc

+1

@KooiInc是的,但非正则表达式的方法是略微。更快 –

相关问题