简体   繁体   English

将DOM从当前状态的DOM追加/复制到div

[英]Appending/Replicating HTML from DOM in current state to a div

I have a form on a page. 我在页面上有一个表格。 The form contains text inputs, checkboxes, selects (interactive elements). 该表单包含文本输入,复选框,选择(交互元素)。 I want the user to be able to click a button, and reproduce a portion of the form elsewhere on the page, in the current state, preserving the text entered, the checkboxes checked, and the selects selected. 我希望用户能够单击一个按钮,并在当前状态下在页面上其他位置重现表单的一部分,从而保留输入的文本,选中的复选框以及选择的内容。

Currently I have this, which appends the HTML, however it grabs the HTML in the state it was when the page was loaded. 目前,我有这个文件,它附加了HTML,但是它以加载页面时的状态抓取HTML。

$('#create_unique_field').click( function() {
    $('#unique_field_cnt').append($('#template_cnt').html());
});

I have tried using delegation using on(), like so, with the same results. 我已经尝试过使用像on()这样的委托来获得相同的结果。

$( 'body' ).on( 'click', '#create_unique_field', function() {
    $('#unique_field_cnt').append($('#template_cnt').html());
});

What I want is the current state of the HTML, not the HTML at the point when the page was loaded. 我想要的是HTML的当前状态,而不是页面加载时的HTML。 How can I accomplish this? 我该怎么做?

It doesn't work that way, you need to bind values of form elements and create new form elements with that data. 那样行不通,您需要绑定表单元素的值并使用该数据创建新的表单元素。 More or less it falls on var inputText = $('#someInputEl').val(); 它或多或少地落在var inputText = $('#someInputEl').val(); and then applying that values on new form elements and THEN inserting it. 然后将该值应用于新的表单元素,然后将其插入。

Try this: 尝试这个:

<input type="text" id='one'>
<button>submit</button>   
<div id="target"></div>   

$(function(){
    $('button').click(function(){
        var inputVal = $('#one').val();
        var newInputEl = $("<input type='text' id='two'>");
        newInputEl.val(inputVal);
        $('#target').html( newInputEl );
    });    
});

This is rough sketch but you should make it work this way, here is fiddle . 这是一个粗略的草图,但是您应该以这种方式使它起作用,这是小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM