动态创建可折叠/分隔符内的列表视图

时间:2013-11-30 21:31:43

标签: listview jquery-mobile dynamic jquery-mobile-collapsible

我正在尝试开发一个应用程序,我正在使用jQuery mobile for UI。有人知道如何使用JavaScript动态地在可折叠(作为类别)中添加列表视图吗?

HTML:

<div data-role="content" id="introContent">
  <p id="introContentNoFeeds" style="display:none">welcome!
  </p>
  <ul id="feedList" data-role="listview" data-inset="true" data-split-icon="delete">
  </ul>
  <a href="addfeed.html" data-role="button" data-theme="b">Add Feed</a>
</div>

JS:

function displayFeeds() {
    var feeds = getFeeds();
    if(feeds.length == 0) {
        //in case we had one form before...
        $("#feedList").html("");
        $("#introContentNoFeeds").show();
    } else {
        $("#introContentNoFeeds").hide();
        var s = "";
        for(var i=0; i<feeds.length; i++) {
            s+= "<li><a href='feed.html?id="+i+"' data-feed='"+i+"'>"+feeds[i].name+"</a> <a href='' class='deleteFeed' data-feedid='"+i+"'>Delete</a></li>";
        }
        $("#feedList").html(s);
        $("#feedList").listview("refresh");
    }   
}
function getFeeds() {
    if(localStorage["feeds"]) {
        return JSON.parse(localStorage["feeds"]);
    } else return [];
}
function addFeed(name,url) {
    var feeds = getFeeds();
    feeds.push({name:name,url:url});
    localStorage["feeds"] = JSON.stringify(feeds);

1 个答案:

答案 0 :(得分:3)

首先,创建一个静态的collapsible-set div data-role="collapsible-set"并为其指定一个id或一个类。

<div data-role="page">
  <div data-role="content">
    <div data-role="collapsible-set" id="stuff"></div>
  </div>
</div>

JS解决方案取决于你的数组结构,我创建了一个简单的解决方案。

/* array */
var data = [{
    "title": "Category 1",
        "items": [
        "one", "two", "three"]
}, {
    "title": "Category 2",
        "items": [
        "four", "five", "six"]
}, {
    "title": "Category 3",
        "items": [
        "seven", "eight", "nine", "ten"]
}];

/* retrieve data from array */
$.each(data, function (i, v) {

    /* store array of listview items */
    var items = v.items;

    /* create a collapsible */
    var col = $("<div/>", {
        "data-role": "collapsible"
    });

    /* collapsible's title - add it to created collapsible */
    var title = $("<h3/>", {
        text: v.title
    }).appendTo(col);

    /* to store retrieved listview items */
    var list_items = '';

    /* read array of listview items */
    $.each(items, function (x, y) {
        list_items += "<li><a href='#'>" + y + "</li>";
    });

    /* create listview */
    var list = $("<ul/>", {
        "data-role": "listview",
           "id": "listview" + i, // if you want to give each listview an id
              "data-inset": true // or false, it's up to you
    });

    /* add listview items to created listview */
    $(list).append(list_items);

    /* add listview to collapsible */
    $(list).appendTo(col);

    /* finally, add them all into collapsible-set */
    $("#stuff").append(col).collapsibleset().trigger("create");
});
  

<强> Demo