0

这是将表单数据加载到字符串然后加载到的最佳方式localStorage吗?

我自己想出了这个,我不擅长编程。它可以满足我的需要,但我不确定它是否是防弹代码?

<script>
    var sg = document.getElementById("selectedGateway");
    var sd = document.getElementById("selectedDestination");
    var dm = document.getElementById("departureMonth");
    var dd = document.getElementById("departureDay");
    var dy = document.getElementById("departureYear");
    var rm = document.getElementById("returnMonth");
    var rd = document.getElementById("returnDay");
    var ry = document.getElementById("returnYear");
    var ad = document.getElementById("adults");
    var ch = document.getElementById("option2");

    $("#searchRequestForm").submit(function() {
        var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value;
        localStorage.setItem("string", string);
    });
</script>
4

3 回答 3

6

我会使用类似下面的东西,这样我就可以处理一个对象及其属性,而不是一个大字符串。请注意,除了 jQuery 选择器之外,这是纯 JavaScript。

演示:http: //jsfiddle.net/grTWc/1/

var data = {
    sg: $("#selectedGateway").val(),
    sd: $("#selectedDestination").val()

    // items here
};

localStorage.setItem("mykey", JSON.stringify(data));

要检索数据:

var data = JSON.parse(localStorage["mykey"]);
alert(data.sg);

也可以看看:

于 2013-04-13T01:24:37.933 回答
2

我更喜欢表驱动的方法,所以没有重复的代码(DRY):

var ids = [
    "selectedGateway", "From: ", 
    "selectedDestination", "\nTo :",
    "departureMonth", "\nDeparture: ", 
    "departureDay", "/",
    "departureYear", "/",
    "returnMonth", " \nReturn: ",
    "returnDay", "/",
    "returnYear",  "/",
    "adults", " \nNumber of adults: ",
    "option2", " \nNumber of children: "];

var submitStr = "";
for (var i = 0; i < ids.length; i+=2) {
    submitStr += ids[i+1] + document.getElementById(ids[i]).value;
}
localStorage.setItem("string", submitStr);
于 2013-04-13T01:33:48.823 回答
0

您可以定义一个如下所示的函数来直接通过 id 获取值,这样在构建字符串时会更简单。

function form(id) {
    return document.getElementById(id).value;
}
于 2013-04-13T01:25:57.347 回答