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

如何读取选中的行(tr)列(td)数据属性

  •  0
  • shamim  · 技术社区  · 7 年前

    在我的MVC项目中,需要找到选中的行(tr),第一个子(td)数据属性和控制标记名也需要设置属性attr(“选中”,“选中”);

    HTML

    <table class="availableProduct">
        <tr>
            <td>
                    <input type="checkbox" class="product-group" data-productid="SAP003" 
                    data-id="Annual-46-4" data-optionid="46">
            </td>
            <!-- FIND THIS -->
            <td>foobar</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="product-group" data-productid="SAP0031" 
                data-id="Annual-46-14" data-optionid="461">
            </td>
            <!-- FIND THIS -->
            <td>foobar2</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="product-group" data-productid="SAP0032" 
                data-id="Annual-46-42" data-optionid="462">
            </td>
            <!-- FIND THIS -->
            <td>foobar2</td>
        </tr>
    </table>
    

    JQuery

        $('table.availableProduct tr').click(function (e) {
           var temp=$(this).find("td:eq(0)").html();
        });
    

    jquery temp变量值如下

    <input type="checkbox" class="product-group" 
    data-productid="SAP003" data-id="Annual-46-4" data-optionid="46">
    

    在此选择上要执行以下操作

    • 读取所有数据属性值
    • 设置attr(“选中”,“选中”);
    • 需要读取标记名
    1 回复  |  直到 7 年前
        1
  •  1
  •   Tushar Gupta - curioustushar    7 年前

    this 引用单击的当前元素

    $(this).find('td .product-group'); 用类查找元素 product-group .

    使用 .data() 获取元素的所有数据属性。

    设置检查使用 .prop() .

    $('table.availableProduct tr').click(function(e) {
      var inp = $(this).find('td .product-group');
      inp.prop('checked', !inp.prop('checked')); // toggle check and uncheck
      var dataAttributes = inp.data();
      console.log(dataAttributes);
    });
    

    Demo

    推荐文章