英文:
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');
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论