【问题标题】:Jquery Mobile makes script execute twiceJquery Mobile 使脚本执行两次
【发布时间】:2013-04-20 01:58:22
【问题描述】:

为什么test 消息会显示两次:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        alert("Test");
    </script>
</body>
</html>

我从 http://jquerymobile.com/demos/1.2.0/docs/about/getting-started.html 复制了标头,当我开始做一些示例时,我注意到我的 javascript 方法被调用了两次。

这是 JsFiddle 中的代码:

http://jsfiddle.net/LsxBW/2/

【问题讨论】:

  • 如果将它包含在 $(function(){}) 中,它会触发一次吗;
  • 好问题。如果我将其括为$(function(){ alert("Test"); }); 它也会触发两次,为什么?
  • 你必须遵守 jQuery mobile 的规则:jsfiddle.net/LsxBW
  • 很好奇。你可以为此制作一个 jsFiddle 吗?
  • 这里是 jsFiddle:jsfiddle.net/LsxBW/2

标签: javascript jquery html jquery-mobile


【解决方案1】:

正如 Explosion Pills 所说的那样,你必须遵守 jQM 规则。至少:

  • 为一个或多个页面使用适当的jQM markup
<div data-role="page" id="page1">
    <div data-role="header">
        <h1>Page Title</h1>
    </div><!-- /header -->
    <div data-role="content">    
        <p>Page content goes here.</p>        
    </div><!-- /content -->
    <div data-role="footer">
        <h4>Page Footer</h4>
    </div><!-- /footer -->
</div><!-- /page -->
$(function() {   
    alert("Test");
});

使用

$(document).on("pageinit", "#page1", function(){
    alert("Test");
});

jsFiddle is here

【讨论】:

    【解决方案2】:

    你可以使用

    $(function() {   
        alert("Test");
    });
    

    .. 没问题,只要你用 data-role="page" 把它放在 div 之外。 页面标记内不允许有脚本标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2011-10-19
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多