Domanda

I want to use jQuery to redirect a person arriving at this page to the link contained in the anchor of the last TD of the first TR in TBODY (not THEAD):

<table id="allprogs" class="tablesorter">
<thead>
  <tr>
    <th>Date</th>
    <th>Speaker(s)</th>
    <th>Program Title</th>
    <th>MP3</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>2012: 05/01</td>
    <td>Speaker</td>
    <td><a href="/products/page">Title</a></td>
    <td><a href="http://www.dummy.com">Download</a></td>
  </tr>
  <tr>
    <td>2012: 04/01</td>
    <td>Speaker2</td>
    <td><a href="/products/page2">Title2</a></td>
    <td><a href="http://www.dummy2.com">Download</a></td>
  </tr>

So far my code is:

$(document).ready(function() {
  var url = $('#allprogs tbody tr:first td:last a').attr('href');
  window.location.replace(url);
});

Loading the page should redirect to http://www.dummy.com. But it appears I'm not targeting the anchor properly. Suggestions?

È stato utile?

Soluzione

Your code seems ok. Not sure what exactly do you want to achieve, seen that is looks ok and should do what you want initially. you can try alerting the variable url and see if you get the right url address.

alert(url);

Click to see result:

Altri suggerimenti

The jquery targeting is actually correct,

it's line window.location.replace(url); that is wrong, a space is required* after .replace in order for the redirection to work.

Your new code will look like this :

$(document).ready(function() {
  var url = $('#allprogs tbody tr:first td:last a').attr('href');
  window.location.replace (url);
});

*EDIT:

As it turns out the space isn't required but more of good practise. Apart from this though the rest of your code is working.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top