jQuery表的每一行

时间:2014-05-09 13:22:31

标签: javascript jquery html

我有一个包含3行的表,我试图遍历表并获取表格每行中链接的title属性,将其分配给变量并将其放入函数中。以下是我正在使用的代码:

$('tr').each(function(){
        //$('.distance').html("hello"); 
        //nodelat = $(this).find('.latitude').html();
        //nodelon = $(this).find('.longitude').html();

        postcode = $(this+".location a").attr('title');

        console.log(postcode);
        //$(this).find('.distance').html(distance(startlat, startlon, nodelat,nodelon));
    });

由于某种原因,它似乎只是重复第一个表行的值3次。我错过了什么吗?

该表的代码是:

<table id="locations" class="tablesorter">
  <tbody>
    <tr>
      <td>Name</td>
      <td>Distance</td>
    </tr>
    <tr>
      <td class="location"><a href="#Dockyard" onclick="getLatLng(&quot;m502st&quot;, &quot;This is a pub&quot;)" title="m502st">Dockyard (show on map)</a></td>
      <td class="distance"></td>
    </tr>
    <tr>
      <td class="location"><a href="#Joseph Holt" onclick="getLatLng(&quot;M3 1JD&quot;, &quot;http://www.joseph-holt.com&quot;)" title="M3 1JD">Joseph Holt (show on map)</a></td>
      <td class="distance"></td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:1)

变化:

$(this+".location a").attr('title');

要:

$(this).children('.location').children('a').attr('title');

或者:

$(this).find('.location > a').attr('title');

JSFiddle demo

答案 1 :(得分:0)

问题在于此$(this+".location a")语句。

尝试

postcode = $(this).find("td.location a").attr('title');
console.log(postcode);