【问题标题】:Add dynamic list items to dynamically created panel with a istview使用 istview 将动态列表项添加到动态创建的面板
【发布时间】:2014-03-05 10:37:50
【问题描述】:

我正在为我的网络项目使用 jquery mobile 1.3.2。

以下代码为所有页面创建一个面板:

function injectPanelIntoAllPages(){
    console.log("IncetPanel");

    var panel = '<div data-role="panel" id="mypanel" data-position="left" data-display="push">' + 
                 '<div><ul data-role="listview" id="history"></ul></div> </div>';


    $(document).on('pagebeforecreate', '[data-role=page]', function () {
        if ($(this).find('[data-role=panel]').length === 0) {
            $('[data-role=header]').before(panel);
        }
        $(document).on('pagebeforeshow', '[data-role=page]', function () {
            $(this).trigger('pagecreate');
        });
    });

}

现在我想将(动态)列表项添加到面板中的列表视图中,但它不起作用。

对于添加列表项,我使用以下方法:

function addToHistory(value) {
    $("#history").append(
            "<li id='history-element'>" + value + "</li>");
    $("#history").listview("refresh");

}

我可以做些什么来解决这个问题?

【问题讨论】:

  • 您想什么时候添加它们?面板创建后?还是在后期?
  • 我在每个页面中都有一些列表项.. 每次单击列表项时,我都想在面板中的列表视图中添加一个值.. -> 稍后阶段

标签: javascript jquery jquery-mobile jquery-mobile-listview


【解决方案1】:

请注意,您对 panellistview 使用相同的 ID。不建议这样做,但是,只要您指定要在 活动页面 中定位哪个 元素,它仍然可以工作。

另外注意,一旦您动态附加面板,您就不需要调用任何enhancement 方法,因为您将它们附加到pagebeforecreate。它们将由 jQM 在该事件中创建/初始化。

$(document).on('pagebeforecreate', function () {
  if ($(this).find('[data-role=panel]').length === 0) {
    $('[data-role=header]').before(panel);
  }
});

要将元素附加到 listview,您需要在 活动页面 中查找它。否则,新元素将添加到 ID 为 #history 的第一个元素。

var listview = $.mobile.activePage.find("#history");
listview.append("elements").listview("refresh");

Demo

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多