任何人都可以提供一个选择器来消除这些可怕的代码:

// 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 元素。

谢谢,结果 ķ

有帮助吗?

解决方案

由于您担心将图像包裹在某物中,请尝试以下操作:

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

最近的命令找到与给定选择器匹配的最近祖先。 请看这里。

其他提示

我想你会听到很多关于这种结构的方式。如果你消除了这个表,很多问题就会消失。

类似的东西:

<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();

当用户点击...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top