将表单数据加载到字符串然后再加载到localStorage的最佳方法是什么?

时间:2013-04-13 01:21:58

标签: javascript jquery

这是将表单数据加载到字符串然后再加载到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>

3 个答案:

答案 0 :(得分: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);

另见:

答案 1 :(得分: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);

答案 2 :(得分:0)

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

function form(id) {
    return document.getElementById(id).value;
}