How do I use array.push to add an object with a custom index in an array?
I have this script but it doesnt work. Chrome's Javascript console is not outputting errors
var tempList = new Array();
$('#add').click(function(){
var split = $('#itemid').val().split('_');
var itemid = split['0'];
var lbs = $('#lbs').val();
tempList.push(tempList['itemid'] = lbs);
for (var i; i<=(tempList.length - 1); i++){
if (i==0){
var list = tempList[i]+ '<br />';
}
else{
开发者_JS百科 var list = list + tempList[i]+ '<br />';
}
}
alert(list);
});
Old answer: Your script may not work, because you have to initialise the index of the loop: var i=0;
Question (new, at the comment chain):
Hi, hope you dont mind another question but how do I display the content of
tempList[]
in a table?
Answer:
See the code below. After the loop, I have included several ways to append the data/table to the body, because you didn't specify which method you wanted.
var tempList = {};
$('#add').click(function(){
var split = $('#itemid').val().split('_');
var returnTable = "<thead><tr><th>ItemId</th><th>Lbs</th></tr></thead><tbody>";
var itemid = split[0];
if(/^\d+$/.test(itemid)) return; //itemId is not a valid number: return now.
var lbs = $('#lbs').val();
tempList[itemid] = lbs; //refer by value, removed quotes around `itemId`.
for (var i in tempList){
returnTable += "<tr><td>" + i + "</td><td>" + tempList[i] + '</td></tr>';
}
returnTable += "</tbody>";
var tbl = document.createElement("table");
tbl.innerHTML = returnTable;
//Various methods to add the table to your document are shown below
// For each example, I assume that that specific element exists
//When the data should be APPENDED to an existing TABLE ("#existingTable")
var tblTo = document.getElementById("existingTable").tBodies[0];
for(var i=0, len=tbl.tBodies[0].rows.length; i<len; i++){
tblTo.appendChild(tbl.tBodies[0].rows[0]);
//Removes the row from the temporary table, appends row to tblTo
}
//When the new table should replace the previous table ("#prevTable"):
var prevTbl = document.getElementById("prevTable");
prevTbl.parentNode.replaceChild(tbl, prevTbl);
//When the table should be APPENDED to a container ("#container")
document.getElementById("output").appendChild(tbl);
//When the new table should replace the contents of a container ("#container")
var container = document.getElementById("container");
container.innerHTML = "";
container.appendChild(tbl);
});
精彩评论