在我的jQuery Mobile应用程序中,我正在创建一些动态页面。这是代码
function createPages()
{
$header = "<header data-role='header'><h1>Dynamically created pages</h1></header>";
$content = "<div data-role='content' class='content'><p>This is a dynamically generated page</p></div>";
$footer = "<div data-role='footer'><h1>Audimax</h1></footer>";
for($i=1;$i<=5;$i++)
{
$section= "<section id='"+"#fav"+$i+"' data-role='page' data-url='"+"fav"+$i+"' class='dynamic'>";
$new_page = $($section+$header+$content+$footer+"</section>");
$new_page.appendTo($.mobile.pageContainer);
}
}
页面正在正确创建并添加到DOM中,我可以导航到它们。问题是我只能将任何事件处理程序附加到动态页面。我使用动态页面的id与jquery“live”但无济于事。非常感谢任何帮助。
答案 0 :(得分:1)
为什么在将新的伪页面添加到DOM时绑定事件处理程序?
function pageShowFunction () {
console.log(this.id + ' has triggered the `pageShow` event!');
}
function createPages()
{
$header = "...";
$content = "...";
$footer = "...";
for($i=1;$i<=5;$i++)
{
$section= "<section id='"+"#fav"+$i+"' data-role='page' data-url='"+"fav"+$i+"' class='dynamic'>";
$new_page = $($section+$header+$content+$footer+"</section>").bind('pageshow', pageShowFunction);
$new_page.appendTo($.mobile.pageContainer);
}
}
通常最好直接绑定到元素而不是委托事件处理。
PS 您没有发布您的事件绑定代码,因此我无法对该代码发表任何具体评论,如果这不能解决您的问题,您可以使用该代码更新您的问题
答案 1 :(得分:1)
将jquery核心升级到1.7.1 http://jquery.com/download/
然后
$(selector).live( eventName, function(){} );
可以在签名
上替换以下内容$(document).on( eventName, selector, function(){} );
然后它适用于动态元素。