【问题标题】:Table with two links - table row clickable - jQuery带有两个链接的表格 - 表格行可点击 - jQuery
【发布时间】:2012-07-04 20:57:44
【问题描述】:

我有一个包含 2 个链接的表格,

  • 如果我点击“按钮”,链接应该指向“page1”

  • 如果我单击整行,则应定位“page2”

我目前被 jQuery Javascript 卡住了 - 有人可以给我建议吗?

HTML & JQuery / JS

<tr>
  <td><a href="page2.html" class="info"><img src="img/img.png" alt="image" class="tlogo"/></a></td>
  <td>Some Text</td>
  <td><a href="page1.html" class="tbutton">Go to page1</a></td>
</tr>

    $(document).ready(function() {
        $('#myTable tr').click(function() {
            var href = $(this).find("a").attr("href");
            if(href) {
                window.location = href;
            }
        });
    });

【问题讨论】:

    标签: jquery hyperlink html-table row href


    【解决方案1】:

    如果您单击按钮,也会触发行单击。阻止这种情况的方法是使用event.stopPropagation();

    这将取消之后将触发的所有事件,因此如果将其放入按钮单击事件中,则不会触发行单击事件。

    【讨论】:

    • ++ 1 event.stopPropogation 确实在下面看到我的帖子演示。 :)
    【解决方案2】:

    尝试类似:

    $(document).ready(function() {
        $('#myTable a').click(function(e){
            window.location = $(e.currentTarget).attr('href');
            e.stopPropagation();
        });
    
        /* Assuming that the link you want to go to on clicking the row is in the first td */
    
        $('#myTable tr').click(function(e) {
            window.location = $('#myTable tr a',e.currentTarget).attr('href');
            e.stopPropagation();
        });
    });
    

    【讨论】:

    • 嗨,一些建议注意:使用event.stopPropogation,并且值得做$('#id tr td a之类的正确映射)只是一些注意:)+1反正:P
    【解决方案3】:

    工作演示 http://jsfiddle.net/5ykup/4/

    API:http://api.jquery.com/event.stopPropagation/it:防止事件在 DOM 树中冒泡,防止任何父处理程序收到事件通知。

    希望对你有帮助,

    代码

       $("table tr").click(function(){
           alert("go to page1");        
        });
    
        $("table tr td a").click(function(event){
            alert("go to PAGE == 2"); 
            event.stopPropagation();
        });
    

    【讨论】:

      【解决方案4】:

      你可以做一件事:-

      <tr>
        <td><a href="page2.html" class="info"><img src="img/img.png" alt="image" class="tlogo"/></a></td>
        <td>Some Text</td>
        <td><a href="page1.html" class="tbutton">Go to page1</a></td>
      </tr>
      
      $(document).ready(function() {
          $('.tbutton').click(function() {            
              window.location.href = page1.html;
          });
       $('"#mytable tr').click(function() {            
                  window.location.href = page2.html;
              });
      });
      


      希望这有帮助:)

      【讨论】:

        猜你喜欢
        • 2015-11-25
        • 2020-11-03
        • 2020-02-17
        • 2011-01-23
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 2015-10-25
        • 2017-12-14
        相关资源
        最近更新 更多