1

有一个 DOM 节点(即:)<p id="myNode">hello world</p>和一个包含它的新替换的原始字符串。

有什么好的技术可以有效实现...

var rawReplacement = `<p id="myNode" updated=true foo="bar">hello world!!!</p>`
document.getElementById("myNode").outerHTML = rawReplacement

但是没有实际使用 outerHTML(它将原始元素与 DOM 分离;丢失事件等)。

4

2 回答 2

2

你可能应该做这样的事情:

var el = document.getElementById("myNode");

el.setAttribute('updated', true);
el.setAttribute('foo', 'bar');
el.textContent = 'new text';

编辑: 为了使其更具动态性,您可以编写如下所示的函数来遍历属性对象及其值并将它们应用于目标元素。

使用 vanilla javascript 似乎您希望实现的目标非常困难,我会考虑使用某种库,可能会做出反应,因为您似乎希望根据状态进行更改。

// Function
function updateElement (element, attributes) {
  for (attr in attributes) {
    element.setAttribute(attr, attributes[attr]);
  }
}


// Use
var myNode = document.getElementById("myNode");
var attributes = {
    updated: true,
    foo: bar
};

updateElement(myNode, attributes);
于 2016-09-13T15:50:27.160 回答
1

基本上你会想要改变元素以单独进行每个更改。要进行您显示的更改,您需要执行以下操作

document.getElementById("myNode").setAttribute('updated', true);
document.getElementById("myNode").setAttribute('foo', 'bar');
document.getElementById("myNode").textContent = 'hello world!!!';

如果您想在任何元素上使用它,您需要更改传递给 getElementById 的参数以匹配您元素的 ID。

使用 setAttribute 将适用于大多数属性,并以 setAttribute(attributeName, attributeValue) 格式工作。有关 setAttribute 如何工作的详细信息,我建议您查看 mdn 文档,因为它们非常广泛地解释了 caviats ( https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute )。

要设置元素的内部,如果要添加 html,则需要设置 innerHtml 属性;如果仅分配文本,则需要设置 textContent 属性(有用,因为您不需要转义 html)

于 2016-09-13T15:49:53.593 回答