对于动态创建的" ul"忽略Jquery data-role选项。项目

时间:2014-03-14 11:52:28

标签: jquery html5 jquery-mobile

我创造了“ul”& “li”元素在JQuery Mobile中动态生成。我已将data-role =“listview”分配给“ul”元素,但这些项目显示为普通的html列表。

我的代码;

<body>
....
<div data-role="content">
<button id="btn" onclick="getList()">Click here</button>
<div id="listDiv"></div>
</div>
<script>
$('#btn').on('click',function(){
$('#listDiv').append('<ul data-role="listview"><li data-role="list-divider">Cars</li><li>BMW</li><li>Audi</li><li data-role="list-divider">Flowers</li><li>Lily</li><li>Rose</li></ul>');
$('ul').listview('refresh');
}
</script>
</body>

3 个答案:

答案 0 :(得分:3)

首次初始化jQuery Mobile框架时,它增强所有内容/小部件。但是,动态注入的元素应通过调用 Widget增强方法手动初始化 / 增强

  • 当您创建新的listview时,您需要致电$("#newList).listview()初始化

    var newList = '<div data-role="listview" id="new"></ul>';
    $("target").append($(newList).listview());
    

    $("target").append(newList);
    $("#new").listview()
    
  • 将元素(li)添加到现有listview时,您需要使用$("oldList").listview("refresh"); 重新增强

    var elements = '<li>Element</li>';
    $("listview").append(elements).listview("refresh");
    
  

<强> Demo

答案 1 :(得分:1)

尝试

$('#listDiv').trigger('create');

<小时/> 更新

$('#listDiv ul').listview();

答案 2 :(得分:0)

  

首先使用Jquery设置数据。例如

$("#id").data(key , value) // like this.
  

这不应该显示在你的HTML中。