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

如何在动态创建的表中使用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.

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

User This

    <table id='myDynamicTable'>
        <tr>
            <td>
                <a href="google.com">redirect to</a>
            </td>
        </tr>

your jquery code is true

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

    window.location=href;
 });