JavaScript -保留"textbox2"值,以便在刷新/重新打开页面后可用

JavaScript - retain "textbox2" value for it to be available after refresh/reopen page

本文关键字:quot 新打开 刷新 textbox2 保留 JavaScript      更新时间:2023-09-26

我有两个文本框。在第一个中写入内容并单击OK按钮后,值也出现在textbox2中。我需要在页面刷新后保存该值,而不是修改,直到有人在textbox1中引入新值并再次点击OK。

<html> 
<head> </head> 
<script type="text/javascript">
function myfunction() 
    { 
     var first = document.getElementById("textbox1").value;
     var textbox2 = document.getElementById("textbox2");
     textbox2.value = first;
    } 
</script>
 <body> 
<input type="text" name="textbox1" id="textbox1" />
<input type="submit" name="button" id="button1" onclick="myfunction()" value="OK" />
<br/>
Your answer is:
<input type="text" name="textbox2" id="textbox2" readonly="true"/>
</body>
</html>

据我所知,您可以通过声明runat="server"使"Textbox2"成为服务器控件,即使在服务器击中后也会保留该值,如下所示。

<input type="text" name="textbox2" id="textbox2" readonly="true" runat="server" />

然后将其存储在会话(在c#的情况下)或服务器端类似的东西中以恢复值。

希望这有帮助!!

每次都应该这样做。http://jsfiddle.net/CKLAg/

首先,简化你的HTML:

<input type="text" name="textbox1" id="textbox1">
<button name="button" id="button1" onclick="myFunction();">OK</button>
<br/>Your answer is:
<input type="text" name="textbox2" id="textbox2" readonly="true">

然后,添加以下函数来检查localStorage, save和load storage的需求:注意,您必须使用jQuery来获取文档就绪状态,并在DOM就绪时设置输入元素。

$('document').ready(function(){
    var prevAnswer = loadStorage;    
    $('#textbox2').attr('value', prevAnswer);
});
function loadStorage() {    
    if (supports_html5_storage) {
        if (localStorage.getItem('myAnswer')) {
            var answer = localStorage.getItem('myAnswer');
            return answer;
        }
    }
}
function myFunction() {
    var first = document.getElementById("textbox1").value;
    var textbox2 = document.getElementById("textbox2");
    textbox2.value = first;
    if (supports_html5_storage) {
        alert('storing');
        localStorage['myAnswer'] = first;
    }
}
function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}