代码之家  ›  专栏  ›  技术社区  ›  g.pickardou

如何在jQuery DOM操作中引用目标?

  •  0
  • g.pickardou  · 技术社区  · 4 年前

    $("input:checkbox").after("<input type='hidden' name='...' value='...'/>");
    

    我想我必须用字符串连接来实现这一点:

    $("input:checkbox").after("<input type='hidden' name='"+ <how to refer here to the target?>+"' value='...'/>");
    

    如何在参数表达式中引用实际目标 after() ? 当使用jQuery事件监听器时,我知道我得到了事件及其 target 属性将是DOM元素,但在这里我被卡住了

    1 回复  |  直到 4 年前
        1
  •  1
  •   CertainPerformance    4 年前

    具有 each ,您将得到一个回调,从中可以引用迭代的元素。

    $("input:checkbox").each(function() {
      // `this` now refers to the input
    
      // maybe you want something like
      $(this).after("<input type='hidden' name='" + this.name + "' etc
    });
    

    $("input:checkbox").each(function() {
      $(this).after("<input name='" + this.name + "'>");
    });
    console.log(document.body.innerHTML);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="foo">