我正在创建一个得分保持应用,需要将玩家的名字和游戏名称保存在本地存储中,不知道如何将其应用到我拥有的代码
$(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>
答案 0 :(得分:1)
答案 1 :(得分:0)
迟到回答但是这样的事情
<input type="submit" value="Submit" id="btn_submit" />
<script type="text/javascript">
$(document).ready(function(){
$("#btn_submit").click(function(e){
e.preventDefault();
var jsonObj = [];
players = {}
count = 0;
$('input[type=text]').each(function(){
if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
players[count++] = $(this).val()
}
});
players['game_name'] = $("#user_input").val();
jsonObj.push(players);
console.log(jsonObj);
var jsonString= JSON.stringify(jsonObj);
localStorage.setItem("jsonString", jsonString);
/* remove localstorage */
// localStorage.removeItem("jsonString");
/* get localstorage */
// console.log(localStorage.getItem("jsonString"));
});
</script>