2013-01-07 149 views
0

当我点击一个链接“zmeniťpozíciu”,我想保存它最接近的img到变量。jquery遍历表

<table border="1"> 
    <tbody> 
     <tr>   
      <th rowspan="3">1</th> 
      <th>Nadpis</th> 
      <td colspan="9">Eiusmod tempor</td> 
      <td> <a href="#">zmeniť</a> </td> 
      <td rowspan="3"> <a class="zmenit-poziciu" href="#">zmeniť pozíciu</a> </td> 
     </tr> 
     <tr> 
      <th>Text</th> 
      <td colspan="9">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam ... 
      </td> 
      <td> <a href="#">zmeniť</a> </td> 
     </tr> 
     <tr class="obrazok"> 
      <th>Obrázok</th> 
      <td colspan="9"> <img alt="img" src="http://lorempixel.com/500/120/sports/1"> </td> 
      <td ><a href="#">zmeniť</a></td> 

     </tr> 

    </tbody> 
</table> 

我试过,但它不工作

$(".zmenit-poziciu").click(function() { 

     var img = $(this).parent().closest("obrazok").html(); 
     alert(img); 
     return false 
    }); 

demo

回答

0

你可以得到这样

$(".zmenit-poziciu").click(function() { 
    var img = $(this) 
      .closest('tr') // get to the tr level 
      .nextAll(".obrazok:first") // find the next tr sibling with class=obrazok 
      .find('img'); // find the img 
    alert(img.attr('src')); 
    return false; 
}); 

http://jsfiddle.net/wirey00/Z5CeE/

0

错误选择使用。

变化: -

var img = $(this).parent().closest("obrazok").html(); 

要: -

var img = $(this).parent().closest(".obrazok").html(); 

使用当前的选择,你实际上是在寻找一个叫obrazok标签,我猜你不有你的文档。

+0

图像可我问为什么你使用(永久使用)'parent()'*和*'nearest()'? –

+0

家长只会让你到'td'的水平 –

+0

@DavidThomas是我们现在应该避免的父母和最亲近的事情吗? – gbtimmon

0

最靠近的是最接近的元素,它与层次结构上面的选择器相匹配。 Docs

从文档:

对于组中的每一个元素,获取通过测试元件本身和DOM树向上遍历通过其 祖先 选择相匹配的第一个元素。

对于您的情况,从点击链接查看层次结构时,tr.obrazok的匹配程度不高。

您将需要遍历DOM并获取DOM中最近元素的东西。这个答案我张贴另一个问题,我认为应该有所帮助:https://stackoverflow.com/a/12873187/921204

你可以用它喜欢:

$(".zmenit-poziciu").click(function() { 
    var img = nextInDOM('.obrazok', $(this)); 
    alert(img); 
    return false 
});