生成动态可点击列表项
我是jquery mobile的新手。 我正在尝试生成动态可点击列表项,其中列表项是来自ajax的名称作为响应。我在第二页中获取每个列表项的Ravi Tamada的电子邮件。 为什么每个列表项的电子邮件ID都没有变化? 我的代码有什么问题吗?
我的剧本:
//When DOM loaded we attach click event to button $(document).on("pageinit","#authors-list-page",function() { //start ajax request $.ajax({ url: “myURL/contacts.json", dataType: "json", success: function(data) { var listItem = ""; for(var i=0;i<data.contacts.length;i++){ listItem += '' + data.contacts[i].name + ' '; } $("#dynamicFieldList").append(listItem).promise().done(function () { //refresh list here $(this).listview("refresh"); //then add click event using delegation $(this).on("click", "li", function () { var currentItem = $(this).index(); alert(currentItem); var newPage = $("Back"+data.contacts[currentItem].name+"
Email: "+ data.contacts[currentItem].email+""); // Append the new page into pageContainer newPage.appendTo($.mobile.pageContainer); // Move to this page by ID '#page' $.mobile.changePage('#secondpage'); }); }); } }); });
contacts.json:
{ "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "ravi@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c201", "name": "Johnny Depp", "email": "johnny_depp@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, . . . . ]}
您正在迭代整个响应,然后设置列表项。
用这个:
for(var i=0;i' + data.contacts[i].name + ''; $("#dynamicFieldList").append(listItem).promise().done(function () { //Your code of function. }); }
使用下面的代码,在side for循环中添加附加代码。
for(var i=0;i' + data.contacts[i].name + ''; $("#dynamicFieldList").append(listItem).promise().done(function () { //refresh list here $(this).listview("refresh"); //then add click event using delegation $(this).on("click", "li", function () { var currentItem = $(this).index(); alert(currentItem); var newPage = $("Back"+data.contacts[currentItem].name+"
Email: "+ data.contacts[currentItem].email+""); // Append the new page into pageContainer newPage.appendTo($.mobile.pageContainer); // Move to this page by ID '#page' $.mobile.changePage('#secondpage'); }); }