【问题标题】:How to find first image tag each property from a table using JQuery如何使用 JQuery 从表中查找每个属性的第一个图像标记
【发布时间】:2017-04-04 05:07:35
【问题描述】:

我的表结构是这样的,

<table id="imagefileUploadValue">
  <tbody>
    <tr><td colspan="3" style="height: 25px;">
      <input type="file" id="fileUploadValue" name="files[]" attrtype="attachment">
      <table id="fileNameTable"></table>
    </td></tr>
    <tr id="deleteRow0">
    <td width="20%" style="height: 25px;">test.json</td>
    <td width="20%">
        <img class="imageIcon" title="edit"   onclick="editImage('test.json','d0adf466ab4fecf1347938fe1f','testfileUploadValue','deleteRow0','cm')">
    </td>
     <td><img class="imageIcon" title="delete" onclick="deleteImage('test.json','d0adf466ab4fecf1347938fe1f','deleteRowl0','cm')">
     </td></tr><tr><td colspan="3" style="height: 25px;"></td></tr></tbody></table>

我正在尝试使用此代码读取该表中第一个图像标记的每个属性,

alert($('#imagefileUploadValue').closest('tr').find("img").find("class"));
alert($('#imagefileUploadValue').closest('tr').find("img").find("title"));
alert($('#imagefileUploadValue').closest('tr').find("img").find("onclick"));
alert($('#imagefileUploadValue').closest('tr').find("img").find("src"));

但我无法获得每个属性。

我在这里做错了什么。有人可以帮忙吗?

【问题讨论】:

    标签: jquery html properties html-table


    【解决方案1】:

    如果您想遍历每个图像的每个属性,您可以使用以下 sn-p 代码。第一行循环遍历&lt;tr&gt;#imagefileUploadValue 内部的每个图像。您可以使用this 获取此循环中的元素。该元素具有一组属性。每个属性都有specifiednamevalue 属性。如果指定,则打印到控制台。

    $('#imagefileUploadValue').find('tr img').each(function() {
      $.each(this.attributes, function() {
        if(this.specified) {
          console.log(this.name, this.value);
        }
      });
      console.log('----'); // separator between the images
    });
    

    你可以在这个 jsFiddle 中测试它:https://jsfiddle.net/k80ajekd/

    【讨论】:

      【解决方案2】:

      您应该使用attr() 来读取元素的属性值。见jquery .attr

      另外,$('#imagefileUploadValue').closest('tr') 不会为您提供表格内的 tr 元素。 (它在dom中搜索父母,而不是孩子。见jquery .closest

      因此,如果您想要表中第一个 img 的属性,请为您要查找的每个属性使用类似的内容:

      $('#imagefileUploadValue').find('img').first().attr('class')

      【讨论】:

        【解决方案3】:

        怎么样:

        $.each(["class","title","onclick","src"], function() {
              console.log($('#imagefileUploadValue tr img:first-child').attr(this));    
        
        });
        

        【讨论】:

        • @ssc-hrep3 我认为问题实际上是如何读取 any 属性,这是 Fredde 正在解决的错误。
        • 我就是这么想的。这是一个循环变体。
        猜你喜欢
        • 2013-04-30
        • 2020-09-03
        • 2021-10-05
        • 1970-01-01
        • 2016-05-27
        • 2016-08-22
        • 1970-01-01
        • 2013-12-21
        • 2011-09-24
        相关资源
        最近更新 更多