我想将不同的数组值传递给onclick函数,当点击按钮显示结果时。单击第一个“显示”按钮时我的预期结果应该是4和5,第二个“显示”按钮应该是5和6.但是我的代码只显示第一个和第二个按钮的5和6,我怎么能得到预期结果?
<table name="itemTable" id="itemTable" style="width:100%">
<tr>
<th style="width:5%"></th>
<th style="width:5%"></th>
<th style="width:50%">2</th>
<th style="width:10%">3</th>
<th style="width:15%">4</th>
<th style="width:15%">5</th>
</tr>
</table>
<script type="text/javascript">
var member_data= [];//if declare here, all all of the row get the latest id
addrow(1);
addrow(2);
function addrow(branch_id){
//var member_data= [];//if declare here will show "member_data is not defined"
member_data= [];
member_data.push({
phone: 123,
name: "aaa",
id: 3 + branch_id
});
member_data.push({
phone: 456,
name: "bbb",
id: 4 + branch_id
});
ttt(branch_id,member_data);
}
function ttt(branch_id,member_data){
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(aaa){
for (var i = 0; i < aaa.length; i++) {
//console.log(aaa[i]);
alert(JSON.parse(aaa[i].id));
}
}
答案 0 :(得分:0)
点击第一个&#34;显示&#34;我的预期结果按钮应为4 5,第二个&#34; Show&#34;按钮应该是5和6.但我的代码只 显示第一个和第二个按钮的5和6。
因为在调用onclick时,成员数据因全局定义而更改,并且每个新按钮的值都会更新。
将您的addRow
方法更改为关注,以便member_data
现在包含所有分支的数据
function addrow(branch_id){
member_data= [];
member_data[branch_id].push({
phone: 123,
name: "aaa",
id: 3 + branch_id
});
member_data[branch_id].push({
phone: 456,
name: "bbb",
id: 4 + branch_id
});
ttt(branch_id,member_data);
}
类似ttt
function ttt(branch_id,member_data){
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, '+ branch_id +')">Show</button>'//this line of show "member_data is not defined"
+ '<input type="text" name="branch" value="'+branch_id+'">';
}
最后show_member为
function show_member(aaa, branchId){
for (var i = 0; i < aaa[branchId].length; i++) {
//console.log(aaa[i]);
alert(JSON.parse(aaa[branchId][i].id));
}
}