我在页面上有这个HTML模板:
<div id="bid_wrapper_[[bid_id]]_[[template]]">
<div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
<div id="bid_delete_[[bid_id]]_[[template]]"><img src="/images/icons/cross.png"></div>
<div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
<div><input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]"></div>
<div><input name="bid_price" id="bid_price_[[bid_id]]_[[template]]"></div>
</div>
</div>我试图删除_[template]文本,并将[bid_id]替换为数字。我试过这个:
var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true)
var new_bid_id = 2
var new_oh = bid_template.outerHTML
new_oh = new_oh.replace(/_\[\[template\]\]/g, '')
new_oh = new_oh.replace(/\[\[bid_id\]\]/g, new_bid_id)在这一点上,如果我是console.log new_oh,这正是我想要的--所有东西都被正确地替换了。但是接下来的几行..。
var new_bid = document.createElement('div')
new_bid.outerHTML = new_oh当我试图设置outerHTML时,这里什么都不会发生。如果设置innerHTML,它确实有效,但我更愿意设置outerHTML。我没有收到任何错误消息,我也不明白为什么它没有设置outerHTML。
发布于 2016-05-12 15:11:04
我假设错误已经发生:'outerHTML‘属性在' element’上,所以element没有父节点。
如果您想用新的div**,创建,那么:**
var div = document.createElement('div');
div.innerHTML = output;
document.body.appendChild(div);如果不是:那么试试这个
var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true);
var new_bid_id = 2;
var parent = document.querySelector('.parent');
var new_oh = bid_template.outerHTML;
var output = new_oh.replace(/_\[\[template\]\]/g, '');
output = output.replace(/\[\[bid_id\]\]/g, new_bid_id);
parent.innerHTML = output;
alert(output)<div class="parent">
<div id="bid_wrapper_[[bid_id]]_[[template]]">
<div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
<div id="bid_delete_[[bid_id]]_[[template]]">
<img src="/images/icons/cross.png">
</div>
<div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
<div>
<input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]">
</div>
<div>
<input name="bid_price" id="bid_price_[[bid_id]]_[[template]]">
</div>
</div>
</div>
</div>
发布于 2016-05-12 15:16:56
您需要首先在文档中插入或追加new_bid div,然后重置其outerHTML。
https://stackoverflow.com/questions/37190395
复制相似问题