我有一个数组和branch_id,我想通过onclick函数传递给javascript添加表行。
var branch_id = 1;
var member_data= [];
member_data.push({
phone: 123,
name: "aaa",
id: 3,
});
member_data.push({
phone: 456,
name: "bbb",
id: 4,
});
addrow(branch_id ,member_data)
将数据和数组传递给addrow函数,并将数组设置为onclick函数中的参数。单击“显示”按钮时,将显示所有数组数据
function addrow(branch_id, member_data){
console.log(member_data)//able to read array
var table = document.getElementById("itemTable");
var tableRow = table.rows.length;
var row = table.insertRow(tableRow);
var cell1 = row.insertCell(0);
cell1.innerHTML =
'<button type="button" onclick="show_member(member_data)">Show</button>'//this line of show "member_data is not defined"
+ '<input type="text" name="branch" value="'+branch_id+'">';
}
function show_member(member_data){
for (var i = 0; i < member_data.length; i++) {
alert(member_data[i]);
}
}
但是我无法将数组传递给onclick,它显示“member_data未定义”。无法将数组传递给onclick函数
答案 0 :(得分:1)
您尚未显示完整的代码,但如果您暂时将show_member(member_data)
更改为show_member("fake data")
,则会收到错误消息,指出show_member
未定义,这告诉我们问题不仅在于找不到member_data,而且确实无法找到show_member
函数。这告诉我们问题是范围。
我重新组织了您的代码,以便将需要访问的项目放入更持久的范围,现在代码运行:
<script>
// These variables and functions are being declared in a higher scope than where
// they will be called from, which makes them accessible to any lower scopes.
var branch_id = 1;
var member_data = [];
member_data.push({
phone: 123,
name: "aaa",
id: 3,
});
member_data.push({
phone: 456,
name: "bbb",
id: 4,
});
function show_member(data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].phone);
}
}
function addrow(branch_id, member_data) {
console.log(member_data)//able to read array
var table = document.getElementById("itemTable");
var tableRow = table.rows.length;
var row = table.insertRow(tableRow);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<button type="button" onclick="show_member(member_data)">Show</button>'
+ '<input type="text" name="branch" value="' + branch_id + '">';
}
window.addEventListener("DOMContentLoaded", function () {
// addrow was declared at a higher scope, so it's accessible here
// We need to have this function call wait until the DOM is loaded
// because it needs to scan the DOM for the table elements
addrow(branch_id, member_data);
});
</script>