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

使用jquery遍历DOM

  •  1
  • HPWD  · 技术社区  · 6 年前

    给定以下HTML DOM:

    <div>
        <div>
            <input data-id="somevalue">
        </div>
        <div>
            <a href="">edit</a>
        </div>
    </div>
    

    单击编辑时,我想获取 somevalue .

    a)我会用吗 .parent().parent().find() 还是有更合适的解决方案?
    b)我如何获得 data-select ?我知道如何通过ID或类来获取它,但不清楚用于数据属性的语法。

    使用以下方法:

    var id = $(this).parent().parent().find().attr('id');
    console.log(id);

    输出 undefined 因此,我不确定是否存在遍历问题,或者是否没有正确的语法来获取数据属性值。

    1 回复  |  直到 6 年前
        1
  •  0
  •   CertainPerformance    6 年前

    你可以用

    $(this).parent().prev().children().data('id')
    

    :

    $('a').click(function(e) {
      e.preventDefault();
      console.log(
        $(this).parent().prev().children().data('id')
      );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
        <div>
            <input data-id="somevalue">
        </div>
        <div>
            <a href="">edit</a>
        </div>
    </div>

    你的 .find() 没有参数,不会给您任何结果,因为您没有传递任何要查找的选择器。此外,还有 属性 不是 id -属性是 data-id ,所以您应该使用 data('id') 而不是 attr('id') .