我有 AJAX 生成的简单文本框。
<input type='text' id='txt1' name='txt1_nm' />
当我按下一个按钮时,我想做什么。输入全部复制到不同的 div 中,并由用户插入新值。
我用
$('#txt1').html();
但是,值不会只复制到文本框
最佳答案
您需要使用clone()
来获取元素及其值。在下面代码段的文本框中输入任何内容,然后按 Copy
按钮。
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the clonned element
var inputElement = $('#txt1').clone();
//add clonned element to a new div
$('#copiedDiv').html(inputElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
如果您想添加多个克隆项,则需要更改 input
元素的 id
,然后将其附加到页面。你可以这样做来实现它,
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the last input item
var $inputEl = $('input[name="txt1_nm"]:last');
//get the next id number
var num = parseInt( $inputEl.prop("id").match(/\d+/g), 10 ) +1;
//clone and set a new id for this element
var $cloneEl = $inputEl.clone().prop('id', 'txt'+num );
//add clonned element to a new div
$('#copiedDiv').append($cloneEl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
关于javascript - 如何复制输入元素及其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762251/