我有一个 div,其中包含可变数量的输入(文本、隐藏)和下拉列表(每个可能有一个 ID、名称和/或一个或多个类。
此 div 会不时重新加载,并且可能会添加一些新输入或删除旧输入。
我想做的是维护每次重新加载之前输入或选择的值,而不将当前值传递到服务器。
这里的代码几乎满足了我的需要,除了选择字段 - 没有获取它们的值;一旦成功,我可以序列化该数组并将其存储在某个地方,然后解码、迭代并将值写回。
function getAllValues() {
var inputValues = [];
$jq('#slip input').each(function() {
var type = $jq(this).attr("type");
if ((type == "checkbox" || type == "radio") && $jq(this).is(":checked")) {
inputValues.push([ getIdentifier($jq(this)), $jq(this).val()]);
}
else if (type != "button" || type != "submit") {
inputValues.push([ getIdentifier($jq(this)), $jq(this).val()]);
}
})
$jq('#slip select').each(function() {
var type = $jq(this).attr("type");
if (type != "button" || type != "submit") {
inputValues.push([ getIdentifier($jq(this)), $jq(this).val()]); // problem!
}
})
return inputValues;
}
希望您提供任何意见或解决此类问题的更优雅的解决方案?
后来编辑:Benjamin 很友善地发布了 jquery serialize() 的链接,这很好地解决了问题。如果其他人需要一些代码来恢复保存的值:
function restoreSlipValues(){
var tickets_data = decodeURIComponent($jq("#temporary-values").val()).split("&");
console.log(tickets_data);//.split("&");
$jq(tickets_data).each(function(){
if (this.split("=")[0] !="authenticity_token" && this.split("=")[0].indexOf("_win") < 0 && this.split("=")[0].indexOf("winning") < 0) {
$jq("form#ticks input[name=\"" + this.split("=")[0] + "\"]").val(this.split("=")[1]);
$jq("form#ticks select[name=\"" + this.split("=")[0] + "\"]").val(this.split("=")[1]);
}
});
}
最佳答案
表单有 .serialize
方法。在您的情况下,这可能是最容易存储在 localStorage 中的。
The
.serialize()
method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types.
(很高兴有帮助)
关于javascript - 通过 jquery.ajax 重新加载后从 div 中恢复输入/选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424590/