2013-07-11 120 views
0

我想建立拉JSON結果回寫到頁面正從JSON陣列功能

到目前爲止,我得到的JSON和當其返回運行是通過一個功能的可重複使用的函數中返回結果一些數據的索引和結果。這一切工作正常

問題是,當我去各地做的結果迭代的功能(如下圖所示)

有時數據結構可能是data.userGroup.form等次data.userGroup。用戶等

我試圖做的是傳遞名稱我想用作函數作爲最後一個參數,即「用戶」和wihin內部.each調用element.name(其中名稱可能會有所不同)但這不起作用。誰能幫忙?

這裏是代碼

$.when(promise).then(function(result) { 

    $(result.data.userGroup).each(function(index, element) { 
    var html = getHTML(["Name", "Delete"], index, element, "user"); 

     $("#accordion2").append(html); 
    }); 

}) 

function getHTML(array, index, element, name) { 

var html = " <div class='accordion-group'>"; 
html = html + "<div class='accordion-heading'>"; 
html = html + "<span class='accordian-image'></span>" + element.name + "</a>"; 
var inner =""; 

    $(element.name).each(function(i, result) { 
    inner = inner + "<tr><td>" + result.name + "</td>" ; 
    }); 

html = html + inner; 
return html; 
} 

回答

1

您需要使用的bracket notation代替dot notationmember operator

element[name] 

防爆

$.when(promise).then(function(result) { 

    $(result.data.userGroup).each(function(index, element) { 
     var html = getHTML(["Name", "Delete"], index, element, "user"); 

     $("#accordion2").append(html); 
    }); 

}) 

function getHTML(array, index, element, name) { 

    var html = " <div class='accordion-group'>"; 
    html = html + "<div class='accordion-heading'>"; 
    html = html + "<span class='accordian-image'></span>" + element[name] + "</a>"; 
    var inner =""; 

    $(element.name).each(function(i, result) { 
     inner = inner + "<tr><td>" + result[name] + "</td>" ; 
    }); 

    html = html + inner; 
    return html; 
}