我将点击事件附加到我页面上的图片中。
$('.ui-block-b img').click(function(event) {}
我使用的是jQuery移动固定页脚。
我尝试使用pagecreate
和pageinit
事件对此进行初始化。
当我点击页脚中的链接(正在加载Ajax),然后返回带有点击处理程序的页面时,pagecreate
和pageinit
正在被重新启动。这附加了另一个点击事件,所以当我点击图像时,会触发2个事件。
我想知道是否有一个jquery Mobile事件来解决这个问题?我是否遗漏了文档中的内容?
我已经通过在附加之前检查事件是否存在来解决这个问题,但似乎jQuery mobile应该有一些东西来处理这个问题?我做完了
var events = $('.ui-block-b img').data('events');
if (typeof events == 'undefined') { // attach handler}
也许jQuery mobile已经解决了这个问题,我只是遗漏了什么?
答案 0 :(得分:3)
您不应该使用新页面加载JS,因为您知道您所遇到的问题是每次创建页面时JS都在运行,并且每次绑定另一个点击事件时都会运行JS。
解决方案是使用本机jQM指针$ .mobile.activePage引用您的元素,该指针在pageshow事件触发后可用。或者通过在pageinit事件中的根页div(而不是文档)中放置一个jQuery on侦听器。
通过使用$('.ui-block-b img').click(function(event) {}
,您可能会将绑定事件附加到多个页面中的元素(因为jQuery会将页面附加到DOM),这就是您正在做的事情。
<script type="text/javascript">
$("div:jqmData(role='page'):last").bind('pageinit', function(){
//your code here - $.mobile.activePage not declared, but you can setup
// "on" events here that handle elements ONLY on this page
//e.g. $(this).on('click', 'img.ui-block-b', function(){});
// this puts a live event listener that only listens for this page
});
$("div:jqmData(role='page'):last").bind('pageshow', function(){
//your code here - $.mobile.activePage works now
});
</script>
现在绑定事件时,您确保只影响当前页面上的元素。
组织这个有点痛苦,所以我在这里概述了一个更好的解决方案:Jquerymobile - $.mobile.changepage