检查表中的第一个单元格是否具有使用jquery的img标记

时间:2017-10-07 10:03:11

标签: javascript jquery html

我有一个HTML表格,如果第一个单元格有img元素,我需要获取相应的字段。

<table id="ImgtableID">
<tbody>
<tr>
<th>img</th>
<th>Title</th>
</tr>
<tr> 
<td><img src=""/></td>
<td>Title</td>
</tr>
<tr>
<td><img src=""/></td>
<td>Title</td>
</tr>
<tr> 
<td>other value</td>
<td>Title</td>
</tr>
<tr>
<td><img src=""/></td>
<td>Title</td>
</tr>
</tbody>

</table>

我尝试了下面的代码,但它没有工作:

$('#ImgtableID').find('tbody td:first-child').each(function() {

if ($('img',this).length > 0) // also "$this.find('img').length" is not worked
{

}
});

5 个答案:

答案 0 :(得分:2)

find('tbody td:first-child') 仅返回一个节点。我在这个提供多个节点的选择器上循环这样:

&#13;
&#13;
$(function () {
  $("#ImgtableID").find("tr").each(function () {
    if ($(this).find("td").first().children("img").length == 1)
      console.log("Found Image");
    else
      console.log("No Image");
  });
});
&#13;
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<table id="ImgtableID">
  <tbody>
    <tr>
      <th>img</th>
      <th>Title</th>
    </tr>
    <tr> 
      <td><img src=""/></td>
      <td>Title</td>
    </tr>
    <tr>
      <td><img src=""/></td>
      <td>Title</td>
    </tr>
    <tr> 
      <td>other value</td>
      <td>Title</td>
    </tr>
    <tr>
      <td><img src=""/></td>
      <td>Title</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

:first-child最初是一个CSS伪选择器,在jQuery中,你只需使用:first

并且,我认为你应该循环<tr>,而不是第一个<td>

试一试:

$(function(){
    $('#ImgtableID tr').each(function() {
        if ($(this).find('td:first img').length > 0) {
            $(this).css('color','limegreen');
            //or anything  you want
        }
    });
});

小提琴: https://www.bootply.com/TVfueIHPIA

答案 2 :(得分:1)

$('#ImgtableID').find('tbody td:first-child')仅从您的表中返回第一个td

您应该使用tr 伪类或{{1}查看表格中的所有get行和td :first-child行方法。

  

eq方法将匹配元素的集合减少为   指定的索引。

使用eq方法。

eq

&#13;
&#13;
let containsImage=$(this).find('td:eq(0) img').length>0;
&#13;
$('#ImgtableID').find('tbody tr').each(function() {
  let containsImage=$(this).find('td:first-child img').length>0;
  console.log(containsImage);
});
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您可以使用此DOM选择器选择img元素中包含的td元素,这些元素是其包含tr元素的第一个子元素:

tbody td:first-child img

然后不清楚你想用它做什么。 例如,如果您想从包含td的元素旁边的img元素中获取某些值, 你可以得到.parent()的{​​{1}}, 然后使用img下一个.next()元素, 例如:

td

答案 4 :(得分:0)

np.reshape (cn_repmat, (1, -1))

OR     $(“#ImgtableID tr:first-child td:first-child img”)。length&gt; 0 - 为你的id表

意味着 如果表的第一个 tr 标记的第一个 td 标记包含 img标记长度将超过0