gpt4 book ai didi

javascript - 无法使用 javascript 更改 outerHTML

转载 作者:行者123 更新时间:2023-11-30 11:58:51 28 4
gpt4 key购买 nike

我在页面上有这个 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。

最佳答案

我假设发生了错误:“Element”上的“outerHTML”属性,因此元素没有父节点。

如果你想用新的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>

关于javascript - 无法使用 javascript 更改 outerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190395/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com