如何保留通过JS onclick函数更改的innerhtml内容 [英] How to keep the innerhtml content that is changed with the JS onclick function
问题描述
这是一个简单的问题,但似乎无法解决. 我希望能够更改链接的innerhtml内容,一旦由单独的链接触发的onclick函数触发了该链接,该链接实际上将用户带到了另一个页面(在网站内部而不是外部网站内部),我可以使用脚本,但是页面重新加载并转到链接指向的其他页面后,想要更改的所需innerhtml内容就会消失.我实际上要保留文本更改的更改,即使重新加载页面并将其带到其他位置也是如此.
this is a simple problem but cant seem to solve it. I want to be able to change the innerhtml content of a link, once is triggered by an onclick function triggered from separate link that actually takes the user to another page (inside the website not external site), I get the script to work but the desirred innerhtml content to be changed dissapears once the page reloads and goes to the other page the link is pointing to. I actually want to keep the change of the text change even if the page is reloaded and taken elsewhere.
脚本看起来像这样:
<script>
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
} //Js script that does the innerHMTL change
</script>
<a href="http://example.com/en/page.html" class="lang-col" onclick=" myFunction()">eng</a> // button that triggers the onclick function but takes the user to another page inside the site
<a href="http://example.com" id="testchange" >Hello</a> // text to be changed by JS and want to keep the change even if the page is reloaded and taken elsewhere
那么我有什么想法可以做到这一点?谢谢
So any ideas how i could do that? Thanx
推荐答案
要使其正常工作,您需要某种存储空间.让我们尝试localStorage:
For this to work you need some kind of storage. Let's try localStorage:
在设置变量之前,您首先要检查是否已进行更改,然后处理事件:
You first check if the changes has been made before setting the variable, then handle your event:
<script>
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
}
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
//this will save the state of the change
localStorage.setItem('textSet', true);
}
//this will change the text when the page is loaded if the change has been made before.
ready(function(){
if(localStorage.getItem('textSet')){
document.getElementById("testchange").innerHTML = "Get Started";
}
})
</script>
这篇关于如何保留通过JS onclick函数更改的innerhtml内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!