【问题标题】:Jquery - Div with link inside and jq.click() functionJquery - 带有内部链接和 jq.click() 函数的 Div
【发布时间】:2011-12-05 11:23:25
【问题描述】:

是否可以在单击 href 链接(在可点击的 div 内)时禁用 jquery 点击?

HTML

<div id="test">
    <a href="http://google.de">google</a>
</div>

JS

$(document).ready(function()
{
    $('#test').click(function() {
        alert('the link was not clicked'); 
    });
});

示例
http://jsfiddle.net/QHQcQ/2/

【问题讨论】:

    标签: jquery triggers hyperlink click


    【解决方案1】:

    我不确定你想要什么,但添加 -

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

    将阻止链接点击触发,并阻止链接点击冒泡到“div”点击事件。

    演示 - http://jsfiddle.net/ipr101/Lf3hL/

    【讨论】:

    • 注意这相当于my answer中的return false
    【解决方案2】:

    是的,你可以使用

    $('#test').click(function(event) {
          event.preventDefault();
    });
    

    event.preventDefault() 使点击无效

    【讨论】:

      【解决方案3】:

      您必须停止在a 上冒泡到div#test 的点击事件。你可以这样做:

      $(document).ready(function() {
          $('#test').click(function() {
              alert('the link was not clicked'); 
          });
          $('#test a').click(function(e) {
              return false;
      
              //equivalent to:
              //    e.stopPropagation();
              //    e.preventDefault();
          });
      });
      

      demo

      【讨论】:

        【解决方案4】:

        您可以使用该事件或简单地返回 false:

        http://jsbin.com/aliwih/edit#source

        $(document).ready(function() { 
          $('#test').click(function() { 
              $("#hello").text('the link was not clicked'); 
              return false;
          });
          $('#test a').click(function() { 
             $("#hello").text('the link clicked'); 
             return false;
          });
        }); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-03
          • 2012-05-05
          • 2011-01-24
          • 2012-12-14
          • 2010-11-02
          • 1970-01-01
          • 2018-09-23
          • 2013-10-26
          相关资源
          最近更新 更多