代码之家  ›  专栏  ›  技术社区  ›  Kieron

一个很好的选择器来删除这个可怕的代码

  •  0
  • Kieron  · 技术社区  · 15 年前

    任何人都能提供一个选择器来消除这段可怕的代码吗?

    // img is the image element...
    var descriptionContent = $(".descriptionContent", img.parent("td").parent("tr").next("tr"));
    

    HTML如下所示:

    <table>
        <tr>
            <td><img /></td>
        </tr>
        <tr>
            <td><div class="descriptionContent" /></td>
        </tr>
        <!-- Repeat n times -->
    </table>
    

    如果用户单击了img,我需要获取下一个(并且只获取下一个) .descriptionContent 元素。

    谢谢,
    K

    2 回复  |  直到 15 年前
        1
  •  5
  •   Walt W    15 年前

    既然您担心将图像包装成某种东西,请尝试以下操作:

    var descriptionContent = $(".descriptionContent", img.closest("tr").next("tr"));
    

    “最近”命令查找与给定选择器匹配的最近祖先。 See here.

        2
  •  0
  •   cgp    15 年前

    我想你会听到很多关于这是一般结构的说法。如果你把桌子去掉,很多问题就消失了。

    类似:

    <div class="imgAndContent">
      <img src="blah.jpg">
      <span class="someDescription">Description.</span> <!-- or div, you choose based on your need -->
    </div>
    

    然后你可以简单地…

    var descriptionContent = $(this).next();
    

    当用户单击时…