【问题标题】:Replace paragraph in HTML with new paragraph using Javascript使用 Javascript 将 HTML 中的段落替换为新段落
【发布时间】:2015-06-23 04:50:08
【问题描述】:

我正在尝试将我的 HTML 文档中的 p 替换为用 Javascript 创建的段落。页面加载后,two 将替换为 t

var two = document.getElementById("two");

document.onload = function myFunction() {
  var p = document.createElement("p");
  var t = document.createTextNode("I am the superior text");
  p.appendChild(t);
  document.getElementById("p");
  document.two = p;
};

【问题讨论】:

  • 您不使用 jquery 有什么原因吗?而且为什么不直接替换p这一段的内容呢?

标签: javascript function onload getelementbyid appendchild


【解决方案1】:

你可以只替换#two元素的文本内容:

var two = document.getElementById("two");

window.onload = function () {
  var t = "I am the superior text";
  two.textContent = t;
};
<p id="two">Lorem ipsum dolor sit amet.</p>

如果您使用createTextNode,那么您需要使用two.textContent = t.textContent 来获取textNode 对象的实际内容。

请注意,您不能通过直接赋值替换 DOM 中的现有节点;这就是你想要做的。

【讨论】:

    【解决方案2】:

    您不能直接将节点替换为文档,您可以尝试使用innerHTML:

    document.onload = function () {
      document.getElementById("two").innerHTML = "I am the superior text";
    };
    

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2013-03-03
      • 1970-01-01
      相关资源
      最近更新 更多