我有两个网页。 eventsCreated和createAnEvent。在createAnEvent中,表单用于允许用户'投入。然后使用以下函数将输入存储到本地存储:
document.addEventListener("DOMContentLoaded",docIsReady);
var createEvent;
function docIsReady(){
createEvent=localStorage.getItem("createEvent");
if (createEvent==null){
CreateEvent=[];
}
else {
createEvent=JSON.parse(createEvent);
}
}
function saveToStorage() {
var one;
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
localStorage["X"]=JSON.stringify(positions);
var r=localStorage["X"];
r=JSON.parse(r);
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
one={"name":nameofevent,"pos":r,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
createEvent.push(one);
localStorage.setItem("createEvent",JSON.stringify(createEvent));
//alert(JSON.stringifys(one));
//alert(one.pos[0]); //to get one position
return false;
}
我为createEvent创建了一个数组,以便存储多个输入,因为不能只创建一个事件。在eventsCreated页面中,我需要在表格中显示用户输入,如下所示:
<table border="1px" id="list">
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</table>
我不确定如何使用javascript来获取用户在createAnEvent页面中输入的事件详细信息并将其显示在表中。 这是javascript:
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i=0; i<one.length; i++) {
var row = table.insertRow(i);
for (var j=0; j<=6; j++) {
var cell = row.insertCell(j);
}
cell[0].innerHTML = "one[0]";
cell[1].innerHTML = "one[1]";
cell[2].innerHTML = "one[1]";
cell[3].innerHTML = "one[3]";
cell[4].innerHTML = "one[4]";
cell[5].innerHTML = "one[5]";
cell[6].innerHTML = "one[6]";
}
}
答案 0 :(得分:0)
我会使用jquery向页面添加元素。
但如果你愿意,可以使用dom。
function addRow() {
var table = document.getElementById("list");
var one = JSON.parse(localStorage["createEvent"]);
for (var i = 0; i < one.length; i++) {
var this_tr = document.createElement("tr");
for (var j=0; j < one[i].length; j++) {
var this_td = document.createElement("td");
var text = document.createTextNode(one[i][j]);
this_td.appendChild(text);
this_tr.appendChild(this_td);
}
table.appendChild(this_tr);
}
这应该适合您或接近它。你的表也是错误的,请纠正它。
<table border="1px">
<thead>
<tr>
<th>Name of event</th>
<th>Positions</th>
<th>Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Points Awarded</th>
</tr>
</thead>
<tbody id="list">
</tbody>
</table>
参见示例: