所以我有一个数组项,总是有7列。使用提供的代码,我可以无错误地显示数组的每个元素。但是,当我尝试像这样最后访问数组时:
<button onclick="delete_item(items[i][6])">Delete</button>
我得到:
Uncaught TypeError: Cannot read property '6' of undefined
at HTMLButtonElement.onclick (account.php:64)
onclick @ account.php:64
我其余的代码是:
for(i=0;i<items.length;i++){
document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img src="'+items[i][5]+'" style="width:8%"><br><b style="font-size:20px;">'+items[i][0]+'</b><br>$'+items[i][1]+'<div style="float:right"><a href="item.php?itemid='+items[i][6]+'&itemname='+items[i][0]+'" style="font-size:20px">Click Here for the Item Information</a></div><br>Seller: '+items[i][2]+'<br>Description: '+items[i][3]+'<br> <button onclick="delete_item(items[i][6])">Delete</button></div>');
document.write('<br>');
}
此外,通过使用<button onclick="delete_item(items[1][6])">Delete</button>
而不是'i',一切正常。是什么原因造成的,因为不应该使用i
答案 0 :(得分:0)
在下面的代码中使用此代码是因为在您的代码快照中,我没有引用索引。从您的阵列读取I kay的内容很浅,但无法使用,请尝试以下代码:
<button onclick="delete_item(items["+i+"][6])">Delete</button>
答案 1 :(得分:0)
您必须在变量周围添加一些引号:
'<button onclick="delete_item(\''+items[i][6]+ '\')">Delete</button>'
let a = ["a","b","c","d","e","f","g"];
let b = ["x","b","c","d","e","f","y"];
let items = [a,b];
var delete_item = function(item){
console.log("delete: " + item)
}
for (i = 0; i < items.length; i++) {
document.write('<div style="border-style:solid;padding:15px;background-color:whitesmoke;"><img style="width:8%"><br><b style="font-size:20px;">' + items[i][0] + '</b><br>$' + items[i][1] + '<div style="float:right"></div><br>Seller: ' + items[i][2] + '<br>Description: ' + items[i][3] + '<br> <button onclick="delete_item(\''+items[i][6]+ '\')">Delete</button></div>');
document.write('<br>');
}
此外,您可以考虑使用document.createElement
和addEventListener
。