如何在不刷新周围内容的情况下使用JavaScript替换HTML中的文本?

huangapple go评论127阅读模式
英文:

How to replace text in HTML using JavaScript without refreshing everything around it?

问题

我制作了这段简单的JavaScript代码,它只是搜索HTML中的某个链接,然后用另一个链接替换它,它按预期工作,但它会刷新周围的一切,实际上破坏了周围的一切。

document.body.innerHTML = document.body.innerHTML.replace(/src="https:\/\/media.discordapp.net\/attachments/g, 'src="https://cdn.discordapp.com/attachments');

我希望它只替换链接,而不刷新周围的一切,使我的解决方案变得无用。我已经花了数小时尝试寻找解决方法。

英文:

I made this simple line of JavaScript that just searches the HTML for a certain link and then replaces it with another, it works as intended but it refreshes everything around it.., quite literally breaking everything around it.

document.body.innerHTML = document.body.innerHTML.replace(/src="https:\/\/media.discordapp.net\/attachments/g, 'src="https://cdn.discordapp.com/attachments');

I expected it to just replace the links and that is it... not refresh everything around it, making my solution useless. I've spent hours trying to find a solution.

答案1

得分: 2

这是你要的代码翻译:

这是因为你正在用另一个完全替换innerHTML 相反你应该仅查找具有你正在寻找的src属性的图像并将其替换为你需要的内容

var images = document.querySelectorAll('img[src^="https://media.discordapp.net/attachments"]');

images.forEach(function(image) {
  image.src = image.src.replace('https://media.discordapp.net/attachments', 'https://cdn.discordapp.com/attachments');
});
英文:

Thats because you are replacing the entire innerHTML with another. Instead you should look just for the images that have the src attribute you are looking for and replace it with that you need:

var images = document.querySelectorAll('img[src^="https://media.discordapp.net/attachments"]');

images.forEach(function(image) {
  image.src = image.src.replace('https://media.discordapp.net/attachments', 'https://cdn.discordapp.com/attachments');
});

huangapple
  • 本文由 发表于 2023年3月10日 00:59:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定