【问题标题】:can't change outerHTML with javascript无法使用 javascript 更改 outerHTML
【发布时间】:2016-09-08 11:50:22
【问题描述】:

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

【问题讨论】:

  • 使用.outerHTML简单地将其附加到页面之前上的元素

标签: javascript replace outerhtml


【解决方案1】:

我假设发生了错误:'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>

【讨论】:

    【解决方案2】:

    您需要先将 new_bid div 插入或附加到文档中,然后重置其 outerHTML。

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2018-12-12
      • 1970-01-01
      • 2018-04-07
      • 2013-09-06
      • 1970-01-01
      • 2017-06-16
      • 2011-05-09
      • 2018-10-21
      相关资源
      最近更新 更多