2

我正在尝试开发一个应用程序,并且我正在将 jQuery mobile 用于 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);
4

1 回答 1

3

首先,创建一个静态可折叠集 divdata-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");
});

演示

于 2013-11-30T23:50:14.073 回答