gpt4 book ai didi

Javascript 替换和追加子项

转载 作者:行者123 更新时间:2023-11-29 16:11:45 25 4
gpt4 key购买 nike

我无法弄清楚如何更改 html 文件中包含的段落中的单词。我需要更改使用替换功能来替换一个词,然后用具有新替换词的段落追加一个新段落。我已经尝试了多种方法,这就是我现在所拥有的。

function replace(){
var str = document.getElementById('para').innerHTML;
var wat = str.replace("ipsum", "World");
var el = document.createChild('p');
document.getElementById('para').innerHTML = wat;
el.innerHTML = wat;
document.body.appendChild('el');
}

replace();

我什至不需要在一个函数中全部使用它,我最近才添加它,因为我所做的其他事情都没有用。

最佳答案

这里有各种各样的问题,但最大的问题是:

var el = document.createChild('p');

没有 document.createChild 函数,因此会抛出一个错误,阻止任何其他代码运行。这就是为什么您看不到 para 的文本得到更新的原因,您对其 innerHTML 的分配在该行之后。

如果您的目标是更新 para 中的文本,不清楚为什么要创建新元素,您可以这样做:

function replace(){
var str = document.getElementById('para').innerHTML;
var wat = str.replace("ipsum", "World");
document.getElementById('para').innerHTML = wat;
}

replace();

请注意,当您为第一个参数传递 replace 字符串时,只会替换 第一个 实例,例如 "lorem ipsum lorem ipsum" 将变为 "lorem World lorem ipsum"。如果要替换所有这些,请使用带有 g(“全局”)标志的正则表达式:

var wat = str.replace(/ipsum/g, "World");

如果您确实想创建一个追加子项,创建它的函数是createElement,并且您追加时不带引号:

var el = document.createElement('p'); // <= createElement, not createChild
// ...
document.body.appendChild(el); // <= No quotes

根据您对问题的评论:

I want to keep the original paragraph there, and then add another one with the original using the replaced word.

好的,那么你不想更新parainnerHTML,你想设置elinnerHTML 代替:

function replace(){
var str = document.getElementById('para').innerHTML;
var el = document.createElement('p');
el.innerHTML = str.replace("ipsum", "World"); // Or possibly using /ipsum/g
document.body.appendChild(el);
}

关于Javascript 替换和追加子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25736733/

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