【问题标题】:jQuery: invoke <a /> sub element of table celljQuery:调用表格单元格的<a />子元素
【发布时间】:2008-12-29 13:34:18
【问题描述】:

是否可以添加一个 jQuery 函数,以便在表格单元格中单击将调用 隐藏的 元素(即 TD 的后代)?

我试过了

$('#table td').click(function() { $(this).find('a').click(); });

另一个变种,但没有运气。

--larsw

【问题讨论】:

标签: javascript jquery dhtml


【解决方案1】:

为什么不将 JavaScript 代码从 href 属性中移出并移到点击事件中? jQuery 是用来编写不显眼的 JavaScript 的。

编辑:

不,但实际上,考虑删除那些隐藏的链接以支持不显眼的 JavaScript。以下是重写了 Corey 示例的相关部分:

JS:

  $(document).ready(function() {
    $('table td').click(function(event) {
      alert($(this).html())
    })
  })

HTML:

<table border="1">
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
</table>

【讨论】:

    【解决方案2】:
    <html>
    <head></head>
    <body>
    <table border=1>
        <tr>
            <td>a1<a href=# onclick='alert("a1")' /></td>
            <td>a2<a href=# onclick='alert("a2")' /></td>
        </tr>
        <tr>
            <td>b1<a href=# onclick='alert("b1")' /></td>
            <td>b2<a href=# onclick='alert("b2")' /></td>
        </tr>
    </table>
    <script src="scripts/jquery-1.2.6.min.js" ></script>
    <script>
        $(function(){
            $('table td').click(function(){ $(this).find('a').click()});
        })
    </script>
    </body>
    </html>
    

    我可以很好地使用上面的那个剪辑。但是,请查看您的 jQuery 选择器前面有一个 # ,除非您的表的 id 为“table”,否则它将失败。

    话虽如此,可能有比隐藏嵌入了 javascript 的标签更好的方法来做你想做的事。

    【讨论】:

    • 很好的观察科里。我同意似乎是 # 导致了问题。它应该是 $('table td)。
    【解决方案3】:

    如果您想避免添加 onclick,这将是一种解决方法:

    $('#table td').click(function() { 
        $(this).find('a').each(function(){ window.location = this.href; });
    });
    
    猜你喜欢
    • 2019-03-03
    • 2015-02-24
    • 1970-01-01
    • 2013-05-13
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    相关资源
    最近更新 更多