【问题标题】:How can I return a href link to it's default behavior after using e.preventDefault();?使用 e.preventDefault(); 后如何将 href 链接返回到其默认行为?
【发布时间】:2015-12-07 03:42:32
【问题描述】:

我更新了我的代码并重新表述了我的问题:

我正在尝试创建以下条件。当单击具有空 href 属性(例如 href="")的链接时,将启动一个模式并阻止该链接的默认行为..

但是,当 href 属性包含一个值 (href="www.something.com") 时,我希望链接能够正常工作,使用其默认行为。

由于某种原因,我的代码无法正常工作。任何帮助表示赞赏。

      // Semicolon (;) to ensure closing of earlier scripting
      // Encapsulation
      // $ is assigned to jQuery
      ;(function($) {
           // DOM Ready
          $(function() {

              // Binding a click event
              // From jQuery v.1.7.0 use .on() instead of .bind()
              $('.launch').bind('click', function(e) {
                var attrId = $(this).attr('attrId');

                if( $('.launch').attr('href') == '') {

                    // Prevents the default action to be triggered. 
                    e.preventDefault();

                    // Triggering bPopup when click event is fired
                    $('div[attrId="' + attrId+'"]').bPopup({
                      //position: ['auto', 'auto'], //x, y
                      appendTo: 'body'
                    });
                }  else {
                  $(this).removeAttribute('attrId');
                  return true;
                }  

              });

          });

      })(jQuery);

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    你的 jQuery 是......非常错误。 $('href').attr('') 正在从元素 <href> 获取空属性...您的意思是:

    if( $(this).attr('href') == '')
    

    【讨论】:

    • 是的,我就是这个意思。谢谢
    • 我改写了我的问题和代码,所以我仍然需要帮助了解为什么它不起作用
    【解决方案2】:

    有几件事:event 未定义,因为您的事件对象简称为e。其次,e.stopPropagation(); 不会做你想做的事。 stopPropagation 只是阻止父事件触发(例如:单击<td> 也会触发对包含<tr> 的单击,除非停止)。

    尝试将 else 语句替换为

    return true;
    

    您的 jQuery 也不正确(如此处其他答案所述)。

    这个答案也可能有帮助:

    How to trigger an event after using event.preventDefault()

    祝你好运!

    【讨论】:

    • 感谢您的详细解释。我看到我使用了事件而不是 e。谢谢你
    猜你喜欢
    • 2017-01-25
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多