2016-03-08 56 views
0

我有一個數組和branch_id,我想傳遞給javascript添加錶行與onclick函數。Javascript-如何傳遞數組添加錶行onclick函數

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

是'member_data'可在控制檯? – daymannovaes

+0

有一個語法錯誤:'name:bbb,'應該是'name:'bbb「',對於'name:aaa'也是如此,它們被解釋爲標識符,而不是字符串。 – RobG

+0

對不起,錯誤,感謝RobG提醒,我已經更新代碼 – Arzozeus

回答

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> 
+0

它沒有去show_member(),當我點擊按鈕顯示,錯誤信息顯示「member_data未定義」 – Arzozeus

+0

抱歉的錯誤,是成員名稱,我已更改代碼,它應該是名稱:「 aaa「和名稱:」bbb「 – Arzozeus

+0

在addrow函數的開頭,該數組能夠讀取,但是當我將它傳遞給onclick =」show_member(member_data)「時,無法進入show_member函數它顯示」member_data不是定義」 – Arzozeus

相關問題