【问题标题】:jquery: keep <a> link clickable in clickable divjquery:在可点击的div中保持<a>链接可点击
【发布时间】:2011-07-29 19:43:12
【问题描述】:

如果用户单击该 div 内的链接,我想要做的是阻止单击该 div。 但不使用 .click(function() {});在链接上。

代码如下:

$('div.feature').click(function() { window.location = $(this).attr('rel');});

这里是 div 的示例内容:

<div id="feature" rel="urlnumberone">
some text
<a href="javascript:topicchange(this);" class="insideLink">Link</a>
</div>

由于某些特定原因我不能使用这样的东西

$('.insideLink').click(function(event){
    event.stopImmediatePropagation();
});

我必须使用这个“topicchange()”函数,有什么办法可以防止事件传播?

谢谢!

【问题讨论】:

  • 为什么你不能使用$('.insideLink').click(topicchange)function topicchange(e){ e.stopImmediatePropagation(); //your code follows }

标签: jquery events html clickable propagation


【解决方案1】:

您提供的示例应该可以工作,只是您的 div 的 id 为“feature”,但在 js 中您的目标是一个类。 jsfiddle.net/SNP3K.

<div id="feature" rel="urlnumberone">
    some text
    <a href="#" class="insideLink">Link</a>
</div>

.

$('div#feature').click(function() { 
    alert('div');
});

$('.insideLink').click(function(event){
    event.stopImmediatePropagation();
    alert('link')
});

【讨论】:

  • 谢谢。但我说的是我不能使用 (.insideLink).click 函数,我必须使用现有的“topicchange()”函数:)
  • 对不起,我误读了这个问题。那么是要求调用这个topicchange函数,还是必须从href调用呢?
  • 要求必须从href调用,再次感谢! :)
【解决方案2】:
<div id="feature" onclick="location.href='index.php';">
   <a href="anotherpage.php">link</a>
</div>

就这么简单!

【讨论】:

    【解决方案3】:
    $(document).ready(function() {
        $('div#feature').click(function() {
            alert('div');
        });
        $('div#feature a').click(function(evt) {
            evt.stopPropagation();
        });
    });
    
    function topicchange(targ) {
        alert('link');
        return false;
    }
    

    这是允许的吗?主题更改函数直接从 href 调用,但阻止传播 click 事件。还是说一切都发生在 topicchange 中?

    【讨论】:

      【解决方案4】:

      根据http://api.jquery.com/bind/,event.stopPropagation 应该允许目标上的其他事件处理程序被执行。您仍然可以从 Href 执行,但您也可以通过忽略它来处理默认点击冒泡到 div。

      完整演示:http://jsfiddle.net/leomwa/qrFQM/

      片段:

      function topicChange()
      {
          alert('Message from Link: After the div mouse event, I can execute');
          return false;
      }
      
      $('div#feature').click(function(evnt)
      {
          var $originatingTarget = $(evnt.target);
          if ($originatingTarget && $originatingTarget.is('.insideLink'))
          {
              alert('Message from Div: Ahh! You clicked on Link...');
              evnt.stopPropagation(); // Allows other handlers on the event.target to be executed.
          }
      });
      

      与@shanethehat 非常相似。

      感谢@shanethehat 要求澄清。

      【讨论】:

      • 您可以执行 xyz 而不是在 topicChange() 中返回 false。
      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      相关资源
      最近更新 更多