繁体   English   中英

JavaScript-保留“ textbox2”值,使其在刷新/重新打开页面后可用

[英]JavaScript - retain “textbox2” value for it to be available after refresh/reopen page

我有2个文本框。 在第一个文件中写入内容并单击“确定”按钮后,该值也会出现在textbox2中。 我需要在页面刷新后保存该值,并且除非有人在textbox1中引入新值并再次单击“确定”,否则不要修改该值。

<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,按需保存和加载存储:注意,必须使用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;
    }
}

暂无
暂无

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

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