将加载的CSS应用于动态创建的HTML

我在JQuery Mobile listView上使用此代码动态添加一些HTML内容:

此代码正在我的index.html文件中加载#page容器

     

在我的notifications-list-view.js我有这个代码:

 $("#unread-notifications").addClass ($.mobile.activeBtnClass); fillList (4) $("#unread-notifications").on ("click", function () { fillList (4); }); $("#all-notifications").on ("click", function () { fillList (10); }); function fillList (count) { var listItemClass = "listItem"; var content = ""; if (!$(this).hasClass ($.mobile.activeBtnClass)) { for (i = 0; i < count; i ++) { content += '
  • '; content += ''; content += ''; content += '
    '; content += '
    '; content += '

    Credit elligibility

    '; content += '

    '; content += 'We have recievede uhdccd uhc cdyucd cduhcd ucdhcd cduhcd ucdcd ucd cuhcd ucdcd ucdbcd ubc ahlan you how are you doing it\'s not good'; content += 'We have recievede uhdccd uhc cdyucd cduhcd ucdhcd cduhcd ucdcd ucd cuhcd ucdcd ucdbcd ubc ahlan you how are you doing it\'s not good'; content += 'We have recievede uhdccd uhc cdyucd cduhcd ucdhcd cduhcd ucdcd ucd cuhcd ucdcd ucdbcd ubc ahlan you how are you doing it\'s not good'; content += 'We have recievede uhdccd uhc cdyucd cduhcd ucdhcd cduhcd ucdcd ucd cuhcd ucdcd ucdbcd ubc ahlan you how are you doing it\'s not good'; content += 'We have recievede uhdccd uhc cdyucd cduhcd ucdhcd cduhcd ucdcd ucd cuhcd ucdcd ucdbcd ubc ahlan you how are you doing it\'s not good'; content += '

    '; content += '
    '; content += '
    '; content += '
  • '; listItemClass = "listItem" + i; } $(".notifications-list").html (content); $(".notifications-list").trigger ("chosen:updated"); } }

    但是之前加载的CSS / JS没有应用。

    如何将CSS样式和JS代码应用于此动态添加的HTML内容?

    谢谢。

    jQM不应用样式(增强)动态添加的元素,应该根据使用的小部件调用增强方法。

    问题是你在页面初始化之前调用了fillList() ,也许你正在使用.ready() 。 您应该监听jQM pagecontainer 事件以运行函数。

    此外,您必须了解jQM在pagebeforecreate事件期间开始增强小部件 ; 完成增强后,会触发pagecreate事件。 如果在pagebeforecreate期间动态添加元素, pagebeforecreate不需要调用任何增强方法,但是,在pagecreate您需要手动增强动态元素,例如.listview("refresh")

    1. fillList()你只需要$(".notifications-list").html(content);pagebeforecreate期间pagebeforecreate它时。

       $(document).on("pagebeforecreate", "#pageID", function () { fillList(20); }); 
    2. fillList()您需要添加增强 $(".notifications-list").html(content).listview("refresh")

       $(document).on("pagecreate", "#pageID", function () { fillList(20); }); 

    如果要在创建和显示页面后调用fillList() ,则需要确定列表视图是否存在于DOM中并已创建。

    • 新鲜/新列表视图 :使用.listview()在动态追加后创建它
    • .listview("refresh") 列表视图 :使用.listview("refresh")将样式应用于新元素