返回页面时,jquery移动事件不受约束

时间:2016-01-06 12:53:40

标签: javascript jquery html jquery-mobile

我正在开发一个jquery移动应用程序,并且遇到将on-change事件绑定到文件输入元素的问题。第一次访问page1.php时,事件会正确触发。但是在访问了另一个jquery站点(page2.php)并且回到page1.php之后,事件没有触发(因为我使用chrome的inspect-tool调试,第二次访问page1-php时事件甚至没有绑定)

我还尝试了不同的页面事件来绑定事件,如http://www.gajotres.net/page-events-order-in-jquery-mobile中所述 和http://www.gajotres.net/prevent-jquery-multiple-event-triggering/

以下是 page1.php 的代码:

$(document).on('pagebeforeshow', '#serialSelect', function(){           
  $("#qrImageSelect").off('change', '#qrImageFile').on('change','#qrImageFile' , function(){
    var selectedFiles = $('#qrImageFile')[0].files;
    serialNumber = readSerialNumber(selectedFiles);
    window.location.href = "page2.php?sn="+serialNumber;
  });      
});
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<form id="qrImageSelect" class="ui-btn ui-body ui-body-a ui-corner-all ui-icon-plus ui-btn-icon-left fileinput-button" accept-charset="UTF-8">
  <span>QR code</span>
  <input type="file" name="qrImageFile" data-role="none" id="qrImageFile" />
</form>

page2.php (相同的jquery版本)

<a href="page1.php" data-role="button" class="serial-model-button">

为什么回到page1时事件没有受到约束? 我将不胜感激任何帮助:)

编辑: 一些背景信息:我想加载一张二维码的图片。 QR码包含serialNumber。根据我要加载相关页面的serialNumber。应该可以从这个站点返回来扫描新的QR码。 Sombody有想法以不同的方式解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我终于找到了问题的原因:

当点击page2.php上的链接时,jQuery实际上只是获取第一个data-role =“page”div的内容并将其插入当前页面(page2.php)。这是默认的AJAX导航(http://demos.jquerymobile.com/1.4.5/navigation-linking-pages/

所以page1.php中的脚本(实际上位于html-header中)根本没有运行。

有两种解决方案: 如果你想保持AJAX导航以获得不错的页面转换,那么在data-role =“page”DIV中移动脚本。 我更喜欢另一种选择:通过向链接添加数据-ajax =“false”来防止AJAX导航。

<a href="page1.php" data-role="button" class="serial-model-button" data-ajax="false" >