我正在尝试向页面动态添加链接,但我的 css 样式仅在每次重新加载后第一次创建列表时应用于列表项。
下面是我的html:
<div data-role="page" data-theme="b" id="selectConfirmation">
<div data-role="header" data-theme="b" >
<a class="cancelSelectConfirmationBtn ui-btn-left" data-role="button" data-icon="arrow-l" data-iconpos="left" data-theme="b">Back</a>
<h1>
Confirmation Events
</h1>
</div>
<div data-role="content" style="font-size: 16px;">
<ul id="eventList" data-role="listview" class="ui-listview"></ul>
</div>
</div>
这是我的 java 脚本中添加链接的部分:
函数创建列表(ceg){
var list = document.getElementById('eventList');
for(i=ceg.length-1,k=0; k<ceg.length; i--,k++){
var check = ceg.charAt(i);
if(check == 1){
var events = configJSON.root.DynamicDef.Application.SB_Primary.add[k]["-Data"].split(";");
var li = document.createElement('li');
li.innerHTML = '<a> ' + events[1] + '</a>';
li.setAttribute('class', 'selectConfirmation');
li.setAttribute('confirmcode', '5');
li.setAttribute('data-theme', 'c');
list.appendChild(li);
}
}
var $list = $(list);
if ($list.hasClass('ui-listview')) {//this listview has already been initialized so refresh it
$list.listview('refresh');
} else {//this list needs to be initialized
$list.trigger('create');
}
gotoConfirmation();
有谁知道为什么在我重新创建列表时 css 样式被删除?
最佳答案
在您的 for
之后循环你可以添加这个代码来检查是否 listview
已由 jQuery Mobile 框架初始化:
var $list = $(list);
if ($list.hasClass('ui-listview')) {//this listview has already been initialized so refresh it
$list.listview('refresh');
} else {//this list needs to be initialized
$list.trigger('create');
}
这需要您删除 ui-listview
来自你的课 <ul>
标记,因此您可以将其用作 jQuery Mobile 框架是否已初始化 listview
的标志。 .
这是一个演示:http://jsfiddle.net/PQ39n/15/
更新
您在评论中声明您收到此错误:
Uncaught cannot call methods on listview prior to initialization; attempted to call method 'refresh'"
您收到此错误是因为您正在尝试 refresh
尚未初始化的列表。我上面的代码将有助于解决这个问题,因为它会检查 listview
是否存在。已初始化并根据 listview
的状态运行正确的代码.
对于刚接触 jQuery Mobile 的开发人员来说,这是一个常见问题,因为有太多不同的事件要绑定(bind)到( pageshow
、 pagecreate
、 pageinit
等)和 listview
在任何这些事件触发时,小部件可能已初始化,也可能未初始化。
关于javascript - 将 lis 动态添加到 ul 时,CSS 样式会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682785/