gpt4 book ai didi

javascript - 如何将用户输入保存到本地存储

转载 作者:行者123 更新时间:2023-11-30 20:55:43 25 4
gpt4 key购买 nike

我正在创建一个记分应用程序,需要在本地存储中保存玩家姓名和游戏名称,不知道如何将它应用到我的代码中

$(document).ready(function() {
$("#add-playername").click(function(e) {
e.preventDefault();
var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
var label = '<label for="data[playername][' + numberOfPlayernames + ']">Playername ' + (numberOfPlayernames + 1) + '</label> ';
var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
var removeButton = '<button class="remove-playername">Remove</button>';
var html = "<div class='playername'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-playername").before(html);
});
});

$(document).on("click", ".remove-playername", function(e) {
e.preventDefault();
$(this).parents(".playername").remove(); //remove playername is connected to this

$("#form1").find("label[for^='data[playername]']").each(function() {
$(this).html("Playername " + ($(this).parents('.playername').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
<div class="gamename">
<label><b>Enter Game Name</b></label>
<input type="text" name="game name" placeholder="Game Name" id="user_input">
</div>
</form>
<form id="form1" method="post">
<div class="playername">
<label for="data[playername][0]">Add Player Name</label>
<input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
</div>
<button id="add-playername">Add Player</button>
<br>
<br>
<input type="submit" value="Submit" />
</form>

最佳答案

  • 通过阻止使用 jquery 的表单提交,在表单提交上使用 jquery 选择器抓取游戏和玩家
  • 为游戏和玩家准备对象
  • 使用 JSON.stringify( your_data_object) function 将对象转换为字符串
  • 使用 localStorage.setItem( 'key' , 'value' ) 保存到 localStorage function

    <script>    
    $('#form1').submit(function(){

    var game_name = $("#form2 #user_input").val();
    var players = [];

    var players_inputs = $("#form1").find("input[name^='data[playername]']");

    $.each(players_inputs, function(){
    var player = $(this).val();
    players.push(player);
    });

    var data = {
    game_name : game_name,
    players: players
    }
    console.log(data);

    // save to localstorage
    localStorage.setItem('game_players', JSON.stringify(data) );
    event.preventDefault();
    });
    </script>

关于javascript - 如何将用户输入保存到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47689172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com