【问题标题】:jQuery: clone a div and insert it after last div with sequential idjQuery:克隆一个 div 并将其插入到最后一个具有顺序 id 的 div 之后
【发布时间】:2014-04-24 03:10:47
【问题描述】:

我需要在同一个类的最后一个div 之后插入一个包含formdiv 的克隆。但是我怎样才能清空所有的表单域呢?我有以下代码:

<span id="add">Add</span>
<div id="0" class="addr">
    <input type="text" name="a">
    <input type="text" name="b">
    <input type="text" name="c">
</div>
<script>
    jQuery(document).ready(function($){
        $('#add').on('click',function() {
            var id = $(".addr:last").attr('id');
            $(".addr:last").clone().attr('id', ++id).insertAfter(".addr:last");
        });
    });
</script>

【问题讨论】:

  • .find() .each() .attr()
  • 试试$('#form')[0].reset();

标签: jquery forms clone insertafter


【解决方案1】:

您可以使用该 div 的 html 来附加它,而不是克隆 div

$('#add').on('click', function () {
        var id = $(".addr:last").attr('id');
        var appendDiv = jQuery($(".addr:last")[0].outerHTML);
            appendDiv.attr('id', ++id).insertAfter(".addr:last");
    });

【讨论】:

  • 谢谢!不确定我是否理解代码实际上在做什么,但它有效! :)
  • 在 jQuery() 函数中,我们将 div outerHTML 作为字符串传递,使其成为 jQuery 对象。
【解决方案2】:
var temp = $(".addr:last").clone()
temp = $(temp).(':input').val('');
$(temp).attr('id', ++id).insertAfter(".addr:last");

【讨论】:

    【解决方案3】:

    尝试使用$(".className").empty();

    Remove all child nodes of the set of matched elements from the DOM
    

    【讨论】:

      【解决方案4】:

      您可以使用以下内容来清理 DIV 中的字段

      $('.addr').find('input:text').val('');
      

      【讨论】:

        猜你喜欢
        • 2011-12-23
        • 2012-02-01
        • 1970-01-01
        • 2014-04-29
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        相关资源
        最近更新 更多