如何使用 JSON 数据填充 jQuery Mobile ListView?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18051227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate a jQuery Mobile ListView with JSON data?
提问by Terry Toh
I'm developing a webapp here using HTML and jQuery Mobile (JQM), so I'm pretty new at this. What I'm trying to do here is to populate a JQM listview with a list of names. Each of this names will link to a new page with personal data being displayed (Full name, address, date of birth, etc).
我在这里使用 HTML 和 jQuery Mobile (JQM) 开发一个 web 应用程序,所以我对此很陌生。我在这里尝试做的是用名称列表填充 JQM 列表视图。这些姓名中的每一个都将链接到显示个人数据(全名、地址、出生日期等)的新页面。
Currently, because of my lack of knowledge, I manually create a new .html file for EACH individual person (e.g. johnDoe.html for a fictional character Mr. John Doe). I then physically link the list elements to this html file via the function.
目前,由于我缺乏知识,我手动为每个人创建了一个新的 .html 文件(例如,johnDoe.html 用于虚构人物 Mr. John Doe)。然后我通过函数将列表元素物理链接到这个 html 文件。
Problem is now I have 100 over individuals to populate that list view. I think that there's an easier way to do this rather than manually creating 100+ html files for all these individual persons right?
问题是现在我有 100 个人来填充该列表视图。我认为有一种更简单的方法可以做到这一点,而不是为所有这些个人手动创建 100 多个 html 文件,对吗?
I heard of this JSON thing that might do the trick, but coming from a background of ZERO computing knowledge, I don't really understand how it works. Will someone please shed some light on how can I do this?
我听说这个 JSON 的东西可能会起作用,但是来自零计算知识的背景,我真的不明白它是如何工作的。有人可以解释一下我该怎么做吗?
Thanks a lot!
非常感谢!
EDIT: I'm using Dreamweaver CS5.5 to do the coding. For this webapp that I'm tasked to develop, I was given a "template" or sorts that uses JQM and Backbone.js. As such, somehow the "multi-page" structure for a single HTML file doesn't seem to work. From what I see in the template, every HTML file has a corresponding JS file that has code that looks like this:
编辑:我使用 Dreamweaver CS5.5 进行编码。对于我负责开发的这个 web 应用程序,我得到了一个“模板”或使用 JQM 和 Backbone.js 的排序。因此,不知何故,单个 HTML 文件的“多页”结构似乎不起作用。从我在模板中看到的内容来看,每个 HTML 文件都有一个相应的 JS 文件,其代码如下所示:
define(['jquery',
'underscore',
'backbone',
'helper',
'views/phr/list',
'text!templates/vpr2.html'
],
function ($,
_,
Backbone,
Helper,
phrListView,
tmpVpr2) {
var view = Backbone.View.extend({
transition: 'fade',
reverse: true,
initialize: function () {
this.phrlistview = new phrListView();
},
render: function () {
$(this.el).append(_.template(tmpVpr2, {}));
console.log("Rendering subelements...");
Helper.assign(this, {
'#phrListView': this.phrlistview
});
return this.el;
}
});
return view;
});
For the HTML pages, they all begin with a <div data-role=header>tag, then a <div data-role=content>, before ending with a <div data-role=footer>, all with their respective content within the opening and closing tags.
对于 HTML 页面,它们都以<div data-role=header>标签开头,然后是a ,然后是 a<div data-role=content>结束<div data-role=footer>,所有内容都在开始和结束标签中。
For my listview in question, the JQM code for the listview will be within the <div data-role=content>part of the HTML file. How can I populate this listview with JSON data then?
对于我有问题的列表视图,列表视图的 JQM 代码将位于<div data-role=content>HTML 文件的一部分中。那么如何使用 JSON 数据填充此列表视图?
(Apologies if I sound extremely noob at this, because I really am >.< Really appreciate the help!)
(抱歉,如果我在这方面听起来非常菜鸟,因为我确实是 >.< 非常感谢您的帮助!)
回答by krishgopinath
Solution
解决方案
Yes. Its possible to have two pages and use one for displaying your data and one to show up the details of the clicked item. I had to pull in some old stuff, a demo I made when jQM was in version 1.1 and change it to modern times. Anyway, considering I have an array like this :
是的。可以有两页,其中一页用于显示您的数据,另一页用于显示单击项目的详细信息。我不得不引入一些旧东西,我在 jQM 1.1 版本时制作的一个演示并将其更改为现代。无论如何,考虑到我有一个这样的数组:
[
{
"id": 0,
"age": 31,
"name": "Avis Greene",
"gender": "female",
"company": "Handshake",
"email": "[email protected]",
"phone": "+1 (845) 575-2978",
"address": "518 Forrest Street, Washington, New York, 3579"
},
{
"id": 1,
"age": 31,
"name": "Dunn Haynes",
"gender": "male",
"company": "Signity",
"email": "[email protected]",
"phone": "+1 (829) 454-3806",
"address": "293 Dean Street, Dante, Oregon, 5864"
}
]
I randomly generated stuff and made it upto 100 elements, just like how you seem to have. I have two pages.
我随机生成了一些东西,并使其多达 100 个元素,就像你看起来的那样。我有两页。
<!--first page -->
<div data-role="page" id="info-page">
<div data-role="header" data-theme="b">
<h1> Information</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="prof-list" data-divider-theme="a" data-inset="true">
<li data-role="list-divider" data-theme="b" role="heading">Names</li>
</ul>
</div>
</div>
<!--second page -->
<div data-role="page" id="details-page">
<div data-role="header" data-theme="b"><a href="#" data-rel="back" data-role="button">Go back</a>
<h1>Employee Details</h1>
</div>
<div data-role="content"></div>
</div>
The first page, #info-pageis for showing data in a listview. The second page, #details-pageis for the info of the clicked item. Thats all you need. Only two pages, not more than that.So every time a click happens, you do the following through JavaScript
第一页#info-page用于在列表视图中显示数据。第二页,#details-page是点击项目的信息。这就是你所需要的。只有两页,不多不少。所以每次点击发生时,你都通过 JavaScript 执行以下操作
- Get the current value of data from the array. Like if you click on the 4th
liin the list, get the 4th object from the array which has all the data. Store it in the data variable of the second page, so that it can be retrieved later. Something like this:
$("#details-page").data("info", info[this.id]);Then, redirect to second page using
changePage, like this :$.mobile.changePage("#details-page");When the second page opens, use the
pagebeforeshowevent to get the data from the page (which you stored into this page when the tag in the previous page was clicked.Use some HTML layout to populate the data. I used jQM's grids.
- 从数组中获取数据的当前值。就像单击
li列表中的第 4 个对象一样,从包含所有数据的数组中获取第 4 个对象。 将其存储在第二页的数据变量中,以便以后检索。像这样的东西:
$("#details-page").data("info", info[this.id]);然后,使用 重定向到第二页
changePage,如下所示:$.mobile.changePage("#details-page");当第二个页面打开时,使用该
pagebeforeshow事件从页面中获取数据(当点击上一个页面中的标记时,您将这些数据存储到此页面中。使用一些 HTML 布局来填充数据。我使用了 jQM 的网格。
That's all folks!
这就是所有的人!
Full code
完整代码
Ive attached the JS used with the HTML. Its self explanatory. Read the inline comments in the code and you'll be able to understand more. Assume infois the array in picture.
我附上了与 HTML 一起使用的 JS。它的自我解释。阅读代码中的内联注释,您将能够了解更多。假设info是图中的数组。
//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
$(document).on("pageinit", "#info-page", function () {
//set up string for adding <li/>
var li = "";
//container for $li to be added
$.each(info, function (i, name) {
//add the <li> to "li" variable
//note the use of += in the variable
//meaning I'm adding to the existing data. not replacing it.
//store index value in array as id of the <a> tag
li += '<li><a href="#" id="' + i + '" class="info-go">' + name.name + '</a></li>';
});
//append list to ul
$("#prof-list").append(li).promise().done(function () {
//wait for append to finish - thats why you use a promise()
//done() will run after append is done
//add the click event for the redirection to happen to #details-page
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
//store the information in the next page's data
$("#details-page").data("info", info[this.id]);
//change the page # to second page.
//Now the URL in the address bar will read index.html#details-page
//where #details-page is the "id" of the second page
//we're gonna redirect to that now using changePage() method
$.mobile.changePage("#details-page");
});
//refresh list to enhance its styling.
$(this).listview("refresh");
});
});
//use pagebeforeshow
//DONT USE PAGEINIT!
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
//get from data - you put this here when the "a" wa clicked in the previous page
var info = $(this).data("info");
//string to put HTML in
var info_view = "";
//use for..in to iterate through object
for (var key in info) {
//Im using grid layout here.
//use any kind of layout you want.
//key is the key of the property in the object
//if obj = {name: 'k'}
//key = name, value = k
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
//add this to html
$(this).find("[data-role=content]").html(info_view);
});
Demo
演示
I've also made a demo where you can read more about this at jsfiddle.net. Here's the link : http://jsfiddle.net/hungerpain/52Haa/
我还制作了一个演示,您可以在 jsfiddle.net 上阅读有关此内容的更多信息。这是链接:http: //jsfiddle.net/hungerpain/52Haa/
回答by ANonmous Change
you can try something like this
你可以试试这样的
Updated
更新
Html Page
网页
<div data-role="page" id="testpage">
<div data-role="content">
<ul data-role="listview" id="listitem" data-divider-theme="a" data-inset="true">
</ul>
</div>
</div>
javascript
javascript
$(document).on("pageinit", "#testpage", function(){
$.getJSON("example.json", function(data){
var output = '';
$.each(data, function(index, value){
output += '<li><a href="#" id="' + data + '">' +data+ '</a></li>';
});
$('#listitem').html(output);
});
});

