Jquery event.preventDefault无法使用shift-click

时间:2013-02-18 22:47:51

标签: jquery click anchor preventdefault

我只是希望用户按住Shift键单击某个操作的锚标签。问题是浏览器中的移动点击URL会在新窗口中打开链接。所以,我自然会使用event.preventDefault(),但在这种情况下,在任何浏览器中它似乎都不起作用。任何帮助将不胜感激!

这是一个jsfiddle:

http://jsfiddle.net/zZea9/

以下是代码:

<a href="#" class="edit">shift-click here</a>

<script>

$('.edit').click(function (e) {
    if (e.shiftKey) {
        e.preventDefault();
        alert('you shift-clicked');
    }
});

<script>

4 个答案:

答案 0 :(得分:1)

你没有在jsfiddle中运行jQuery。一旦包含它,你应该首先防止默认,然后检查shift键并运行必要的代码。

你应该尽量避免使用stopPropogation,除非你确实想要阻止事件冒泡DOM。但在这个例子中,这看起来并不像你想要的那样。

看看这里: http://jsfiddle.net/zZea9/3/

$('.edit').click(function (e) {
    e.preventDefault();
    if (e.shiftKey) {
        alert('you shift-clicked');
    }
});

进一步阅读preventDefault: event.preventDefault() vs. return false

答案 1 :(得分:0)

您没有包含jQuery,因此您的点击处理程序未被调用。

HTML

<a href="#" class="edit">click here</a>

JS

$('.edit').click(function(e) {
    if (e.shiftKey) {
        alert("shift+click")
    } 
});

http://jsfiddle.net/fJHug/

答案 2 :(得分:0)

这是根据你想要的工作jQuery代码。

$('.edit').click(function(e) {
    if (e.shiftKey) {
        alert("shift+click");
        e.preventDefault();
    } 
});

$('.edit').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
});

答案 3 :(得分:0)

由于您删除了其他问题:“完整代码”中未阻止默认值的原因很简单:

  

SCRIPT1006:预期')'
  _display,第131行第5个字符

始终检查控制台是否有错误。它们是代码无效的首要原因。

在这种情况下,您忘记了)关闭click()函数调用。