Jquery 查找包含图像的下一个td

Jquery 查找包含图像的下一个td,jquery,Jquery,我有一张这样的桌子 <table> <tr> <td> <img> <div></div> </td> <td></td> <td></td> </tr> <tr> <td></td> <td></td>

我有一张这样的桌子

<table>
  <tr>
    <td>
      <img>
      <div></div>
    </td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>
      <img>
      <div></div>
    </td>
    <td></td>
    <td></td>
  </tr>
</table>

当我点击一个图像时,我需要找到下一行包含一个图像的td,并在它前面添加另一行。 我试过了,但没用

$(this)
  .closest("tr")
  .next("tr:has(td:has(img))")
  .before("<tr><td style='border-right: hidden'></td><td colspan='999'>" + $(this).next().html() + "</td></tr>");
$(此)
.最近的(“tr”)
。下一步(“tr:has(td:has(img)))
.before(“+$(this).next().html()+”);

任何人都可以帮助我吗?

你可以在TR中获取你的图像的当前索引。虽然我建议使用类,但如果这是你需要的,这就足够了。我添加了一个alt文本和边框,只是想看看发生了什么

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>    
<table border=1>
      <tr>
        <td><img alt="sample"><div></div></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td><img alt="sample"><div></div></td>
        <td></td>
        <td></td>
      </tr>
    </table>

对于JS代码,我使用了delegate,以防添加的图像也需要单击。在这里,我获取当前索引,然后检查是否有下一项,然后将其递增到下一项

$("table").on('click','img',function(){
  //get current index
  var index = $("tr img").index(this);

  //get total item count 
  var count = $("tr img").length;
  //check if has next tr with img
  if (index < (count - 1)){
    index++;
    //we need to get the next tr with image then move element up to parent tr to insert row before it
    $("tr img:eq("+ index + ")").closest('tr').before('<tr><td><img alt="sample_new"><div></div></td> <td></td><td></td></tr>');
  }
});
$(“表”)。在('click','img',function()上{
//获取当前索引
var指数=$(“tr img”)。指数(本);
//获取项目总数
变量计数=$(“tr img”)。长度;
//检查img是否有下一个tr
如果(索引<(计数-1)){
索引++;
//我们需要用image获得下一个tr,然后将元素向上移动到父tr,以便在它前面插入行
$(“tr img:eq(“+指数+”))。最近('tr')。在('')之前;
}
});
运行此命令时,您将看到在下一个带有图像的行之前添加了一个新行。 您可以找到工作代码


为了提高效率,您可能希望使用复制隐藏的空行,以便更容易编辑

您的逻辑几乎正确,只需使用
nextAll()
,因为您要查找的元素不是下一个同级元素。如果只想查找下一个实例,那么您只需要使用
:first
。最后,
tr:has(img)
是查找行所需的全部,也不需要
td:has()
。试试这个:

$('img')。单击(函数(){
$(this.nextest(“tr”).nextAll(“tr:has(img):first”).before(“”+$(this.next().html()+“”)
});

第一组
1.
2.
3.
4.
5.
第2组
6.
7.