将 innerHTML 包装在 div 中

Wrap innerHTML in div

我有一个 JS 函数,可以在变量更改时更新产品描述。这里是更新元素的地方。

    Product.Config.prototype.updateProductShortDescription = function(productId) {
var shortDescription = this.config.shortDescription;
if (productId && this.config.childProducts[productId].shortDescription) {
    shortDescription = this.config.childProducts[productId].shortDescription;
}
$$('#product_addtocart_form div.short-description').each(function(el) {
    el.innerHTML = shortDescription;
});
};

效果很好,但希望将输出包装在 div 中。有谁知道在更新标签之前将 innerHTML 包装在标签中的方法吗?

谢谢。

如果您只是设置文本,请不要使用 innerHTML。它非常不安全,并且会愉快地执行脚本并联系您正在使用的文本可以通过简单地包含一些恶意 HTML 代码来指示浏览器执行的任何服务器。

改用 .textContent 属性。

但更好的是,既然看起来你正在使用 jQuery,那么只需使用 jQuery 的内置方式根据需要构建元素:

let div = $(`<div></div>`).text(description);
$(`.my-element`).append(div);

如果您已经有元素:

let update = $(`<div></div>`).text(description);
$(`#your.query-selector goes:here()`).empty().append(update);

(因为 jQuery 允许您以一种方式链接调用,使它们适用于选择中的每个元素,这会将 div-wrapped 描述设置为查询中每个元素的内容结果)

我不知道你的 $$ 函数来自什么,但我在 vanilla JS 中有一个建议:

const descriptionText = "my short description";
const descriptionElements = document.querySelectorAll('#product_addtocart_form div.short-description');

Array.from(descriptionElements).forEach(function(el) {
  const newDiv = document.createElement('div');
  newDiv.classList.add('customDiv');
  newDiv.textContent = descriptionText;
  el.appendChild(newDiv);
});
div {
  border: 1px dotted silver;
  padding: .5em;
  margin: .25em;
}
<div id="product_addtocart_form">
  <div class="short-description">1</div>
  <div class="short-description">2</div>
  <div class="short-description">3</div>
</div>

编辑:

阅读您的第一条评论后,您只需在代码中替换:

  el.innerHTML = shortDescription;

作者:

  const descWrapper = document.createElement('div');
  descWrapper.innerHTML = shortDescription;
  el.appendChild(descWrapper);