代码之家  ›  专栏  ›  技术社区  ›  Al.

jQuery div onclick单击div中的href

  •  7
  • Al.  · 技术社区  · 15 年前

    我有以下HTML:

    <table class="products">
      <tr>
        <td>Product description probably goes here</td>
        <td><a href="#">more information</a></td>
      </tr>
    </table>
    

    $(document).ready(function(){
      $('table.products tr').click(function(){
        $(this).find('a').click();
        return false;
      });
    });
    

    但我认为它进入了一个无限循环或者其他什么。Safari展示了这一点:

    RangeError:最大调用堆栈大小 超过。jquery.min.js:12

    谁能提供一个解决方法或更好的方法?

    7 回复  |  直到 15 年前
        1
  •  9
  •   Stefan Kendall    15 年前

    这里的问题是a位于tr.Ergo中,当触发a click()方法时,事件会冒泡到包含它的tr,从而创建您提到的递归循环。而不是打电话 .find('a').click() ,两者都有 a tr 使用相同的单击方法。

    $('tr, a').click(function(){
       //dostuff
       return false;
    });
    
        2
  •  6
  •   yannickoo    13 年前

    e.stopPropagation();

    $(document).ready(function() {
      $('table.products tr').bind('click', function() {
        $(this).find('a').click();
        return false;
      });
    
      $('table.products tr a').bind('click', function(e) {
        e.stopPropagation();
      });
    });
    
        3
  •  4
  •   Zack    12 年前

    这是一个相当晚的答案,但我发现这是一个非常简短和简单的解决方案:

    $('ul li').bind('click', function() {
        location = $(this).find('a').attr('href');
    });
    
        4
  •  1
  •   Yossi Dahan    13 年前

    bind('click') 而不是 click() 捷径,在几乎相同的情况下对我有效。

        5
  •  0
  •   Shawn    15 年前

    首先,我会 console.log($(this).find('a')) 并确保它是适当的链接。 接下来,我相信点击事件不是你想要的 a 要素我想你只是想: var a = $(this).find('a'); if (a) document.location.href = a.attr('href');

    但我的JavaScript非常弱:)

        6
  •  0
  •   Brad    12 年前

    我的是下拉列表中的一个列表项,因此我希望事件继续冒泡,以便关闭下拉列表。这是我使用的解决方案:

    $('div#outer').click(function (e) {
       if (e.target == e.currentTarget) // prevents bubbled events from triggering
          $($(e.currentTarget).children()[0]).trigger('click');
    });
    
        7
  •  -2
  •   andres descalzo    15 年前
    $(document).ready(function(){
      $('table.products tr').click(function(e){
        e.stoPropagation(); // for stop the click action (event)
        $(this).find('a').click();
        return false;
      });
    });