我想将div的所有内容复制到另一个div中,但在复制之前我需要更改所有输入字段名称和ID。请参阅下面的代码。
<div id="first_div">
<input type="text" name="firstname" id="firstname">
<select name="marital_status" id="marital_status">
<option value="1" selected='selected'>Select</option>
<option value="2">Single</option>
<option value="3">Married</option>
</select>
</div>
<div id="second_div">
</div>
现在我想将first_div的内容复制到second_div中,但在复制之前我需要将输入字段firstname更改为last_name,该怎么做?
答案 0 :(得分:6)
正如我看到你在问题中标记了jQuery,你可以使用jQuery clone方法快速入门:https://api.jquery.com/clone/
var clone = $("#first_div").clone();
然后像这样修改clone innerHTML
clone.find("#firstname").attr("id", "lastname"); // modifying div id
// do the same for every element you want to modify id, etc
//then finally append it to the second_div
$("#second_div").html(clone.html());
答案 1 :(得分:1)
如果你想要一个vanilla Javascript版本:
JSONObject wholeJson = new JSONObject(jsonStringAsDescribedAbove);
JSONString field2 = wholeJson.getJSONString("field2"); // will contain value2
JSONObject field1 = wholeJson.getJSONObject("field1"); // will contain the whole field1 object
JSONString nestedField1 = wholeJson.getJSONObject("field1").getJSONString("nestedField1"); // or field1.getJSONString("nestedField1");, will contain nestedValue1
JSONString nestedField2 = wholeJson.getJSONObject("field1").getJSONString("nestedField2"); // or field1.getJSONString("nestedField2");, will contain nestedValue2
如果你没有在你的解决方案中添加jQuery,那么最好不要添加它,如果只是用它。
答案 2 :(得分:0)
使用纯javaScript
var fdiv = document.getElementById("first_div");
var clnNode = fdiv.cloneNode(true);
var clnInput = clnNode.querySelector('#firstname');
clnInput.setAttribute('id', 'lastname')
var secDiv = document.getElementById('second_div')
secDiv.innerHTML = clnNode.innerHTML;
答案 3 :(得分:0)
只需复制内部html并替换id:
var html = document.getElementById('first_div').innerHTML;
html = html.replace(/firstname/g, 'last_name');
document.getElementById('second_div').innerHTML = html;
<div id="first_div">
<input type="text" name="firstname" id="firstname">
<select name="marital_status" id="marital_status">
<option value="1" selected='selected'>Select</option>
<option value="2">Single</option>
<option value="3">Married</option>
</select>
</div>
<div id="second_div">
</div>