jquery遍历表

时间:2013-01-07 17:08:49

标签: jquery jquery-traversing

当我点击链接“zmeniťpozíciu”时,我想将其最接近的img保存到变量。

<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

3 个答案:

答案 0 :(得分:0)

使用了错误的选择器。

变化: -

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

要: -

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

使用您当前的选择器,您实际上正在寻找一个名为obrazok的标签,我猜您在该文档中没有这个标签。

答案 1 :(得分:0)

Closest为您提供与层次结构上方的选择器匹配的最近元素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
});

答案 2 :(得分: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/

相关问题