感谢这里的优秀人员,我能够整理出我之前遇到的问题的工作原型(prototype) - 使用带有密码要求的文本框输入来填充元素。
现在,一切都按预期进行 - 然而,我注意到一个怪癖,我希望有人可以帮助我。当为我的浏览器 session 输入新值时,将反射(reflect)该更改,但是,访问同一页面的其他任何人都将看到已设置的初始值。
此处为 HTML:
<input id="txtBox" type="textbox" value="0" style="display:none;" />
<input id="txtBox2" type="textbox" value="0" style="display:none;" />
<input id="passwordBox" type="password" value="" style="display: none;" />
<div id="txtBoxValue" style="height: 25px; background: #e3e3e3; width: 100px;"></div>
<div id="txtBox2Value"></div>
这里是 JavaScript:
$(function() {
$('#txtBoxValue').on('click', function() {
$(this).hide();
$('#txtBox2Value').hide();
$('#passwordBox').show().focus();
});
$('input#passwordBox').bind('keypress', function(e) {
if(e.keyCode == 13) {
if($(this).val() == 'password') {
$(this).val('');
$(this).hide();
$('#txtBox').show().focus();
$('#txtBox2').show();
}
else {
$(this).val('');
$(this).hide();
$('#txtBoxValue').show();
$('#txtBox2Value').show();
}
}
});
$('#txtBox').bind('keypress', function(e) {
if(e.keyCode == 13) {
var that = $(this);
$('#txtBoxValue').text(that.val()).show();
that.hide();
}
});
$('#txtBox2').bind('keypress', function(e) {
if(e.keyCode == 13) {
var that = $(this);
$('#txtBox2Value').text(that.val()).show();
that.hide();
}
});
});
您可以在此处查看 jsfiddle:http://jsfiddle.net/curtisrichins/Q22tG/21/
如何最好地保留新信息以便向任何访问者显示,而不是默认返回原始条目值?
最佳答案
您将需要在服务器上存储状态 - 否则无法使所有访问者都可以进行更改。您没有说明您正在使用什么服务器端语言,但此状态可以保存在数据库或类似的数据库中。
因此,就客户端代码而言,您需要使用 ajax 请求(或整页回发)将数据POST
返回到服务器,以便能够存储它。然后,在客户端代码中,您需要允许该数据的 GET
(再次使用 ajax 或类似方法)。
鉴于此,您的代码将被更新为与以下内容类似的内容:
$(function () {
//Load data from server
$.get("/yourserver/handler", function(data) {
$('#passwordBox').val(data);
});
//Send data to server event handler
$('#passwordBox').blur(function() {
//Ajax POST to server
$.post("/yourserverurl/handler", { valueToSave: $(this).val() });
}).fail(function() { alert("Could not save to server"); });
//All the other event handlers, etc that you had before
//...
//...
});
从上面,我展示了在文本框中使用 blur
将数据发送到服务器,但这可以是任何东西 - 单击按钮或其他任何东西。
关于javascript - 将动态输入的文本从 jquery 保留到 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490951/