简体   繁体   English

无需重新加载页面即可替换文本

[英]Text replace without reloading the page

I want to change the text without reloading the page.我想在不重新加载页面的情况下更改文本。

let text = document.getElementById("main").innerHTML; 
document.getElementById("main").innerHTML = text.replaceAll("View more", "Read more");

This code works.此代码有效。 The problem is that when there is pagination (..../shop/?page=1) on the page, it doesn't show the text change.问题是当页面上有分页 (..../shop/?page=1) 时,它不显示文本更改。 Only when I refresh the page does the change occur.只有当我刷新页面时才会发生变化。 What to add to the code to make the text change happen without reloading the page?要在代码中添加什么才能在不重新加载页面的情况下更改文本?

I tried using我尝试使用

window.location.reload();

but it didn't help.但它没有帮助。

One way to achieve this is by using JavaScript's history API to update the URL without reloading the page.实现此目的的一种方法是使用 JavaScript 的历史记录 API 更新 URL 而无需重新加载页面。 Here's an example of how you can modify your code to do this:以下是如何修改代码以执行此操作的示例:

let text = document.getElementById("main").innerHTML; 
document.getElementById("main").innerHTML = text.replaceAll("View more", "Read more");

// Use the history API to update the URL
history.pushState({}, '', '/shop/?page=1');

I don't want it to update the URL.我不希望它更新 URL。

What I meant was that if there is in the URL a /?page=1 it does not change the text我的意思是,如果 URL a /?page=1它不会更改文本

Example of:示例:

test.com/shop - change the text "View more" to "Read more", no need to refresh test.com/shop - 将文本“查看更多”更改为“阅读更多”,无需刷新

test.com/product - change the text "View more" to "Read more", no need to refresh test.com/product - 将文本“查看更多”更改为“阅读更多”,无需刷新

test.com/shop/?page=1 - no text change "View more" to "Read more", works after refresh test.com/shop/?page=1 - 没有文本将“查看更多”更改为“阅读更多”,刷新后有效

test.com/shop/?filters=cars - no text change "View more" to "Read more", works after refresh test.com/shop/?filters=cars - 没有文本将“查看更多”更改为“阅读更多”,刷新后有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM