douan6815 2014-10-05 21:27
浏览 48
已采纳

如何在动态创建的表中使用jQuery重定向到单击的TR?

I have jQuery code that works beautifully for clicking a row in a table that exists at page-load and getting redirected to a new page:

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

I have a second table that gets generated by a jQuery POST and is added dynamically and I know it works because I can alert() myself when I click on a row of a dynamically-created table:

$(document).on('click', '#myDynamicTable tr', function(e) {
 var href = $(this).find("a").attr("href");
 alert(href); 
 });

Obviously, href is undefined. So what code can I use to replace the alert() line with an actual redirect to the link that's in that particular TR?

Update with HTML code: A sample HTML code that is returned via POST to the main page where the user clicks TRs:

<table id='myDynamicTable' border="1" cellspacing="0" cellpadding="10">
<tr><a href="http://address.com/page.php"></a><td>1</td></tr>
<tr><a href="http://address.com/page.php"></a><td>2</td></tr>
</table>

Again, the only difference between this dysfunctional table row clicking and other tables on the same page is the fact that myDynamicTable is generated dynamically via jQuery based on a search string put into an input type="Text" by the user.

  • 写回答

2条回答 默认 最新

  • doufu2496 2014-10-05 21:37
    关注

    If you just want to change the browser URL, just set window.location:

    Presumably your have anchors inside TDs inside your TRs (you should show sample HTML too).

    $(document).on('click', '#myDynamicTable tr', function(e) {
         var href = $(this).find("a").attr("href");
         window.location = href; 
     });
    

    Technically you are meant to set window.location.href, but all browsers allow the shortcut. Javascript: Setting location.href versus location

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?