【问题标题】:ASP.NET MVC + JQuery Mobile event handlersASP.NET MVC + JQuery Mobile 事件处理程序
【发布时间】:2012-11-29 06:56:31
【问题描述】:

我有具有这种布局结构的 ASP.NET MVC 3 + JQuery Mobile 应用程序:

<body>
    <div class="page" data-role="page" data-add-back-btn="true" id="page">
        <div data-role="header" data-position="fixed"></div>
        <div data-role="content" id="content">
            @RenderBody()
        </div>
        <div id="footer" data-role="footer" data-position="fixed"></div>
    </div>
</body>

问题是,绑定到窗口的事件处理程序卡住了几个页面。

例如,我有 2 个页面:"Index""About"。在"Index" 中,我绑定了一些处理程序(比如$(window).click() 事件上的console.log("index"))。但是当我转到"About" 页面时 - 这个处理程序仍然处于活动状态。

有没有办法只在适当的页面处于活动状态时才保留处理程序?

【问题讨论】:

    标签: jquery asp.net asp.net-mvc-3 jquery-mobile jquery-events


    【解决方案1】:

    在 jQM 中使用这种事件绑定:

    $('#page').bind('click', function(e) {
    
    });
    

    对于较新版本的 jQuery,使用 .on( 和 .off( 绑定/取消绑定事件。$('#page') 是您的页面。

    这个:

    $(window).click()
    

    会将它绑定到窗口,因为 jQM 页面是单个窗口事件,每次都会触发。 您还需要担心多事件绑定,here您可以找到有关此问题的更多信息。

    【讨论】:

    • 不幸的是,我需要准确处理窗口事件(滚动),因此在我的应用程序上下文中无法绑定到某个内部容器。
    • 那你需要想办法绕过它,jQM web app是一个单窗口的app。你在用窗口事件(滚动)做什么?
    • 无限滚动。我已经尝试过基于 iscroll 的插件,但它们在某些平台上有点错误。现在我正在寻找在不使用窗口对象的情况下实现无限滚动的方法——希望它能帮助解决这个问题。
    • Berker Yüceer:在Index中定义。
    【解决方案2】:

    我对这个问题做了一些小研究,但没有找到任何合适的问题。 所以我已经用窗口事件为描述的用例实现了解决方案。这令人毛骨悚然,但很有效。

    在布局中:

    1.Page div声明:

    <div class="page" data-role="page" data-add-back-btn="true"    id="@Request.RawUrl.GetHashCode()">
        ...
    </div>
    

    2.脚本:

    <script type="text/javascript">
        var bindEvents = [];
        $(document).bind('pagehide', function (event) {
            var hash = $(event.target).attr('id');
            $(window).unbind('.' + hash);
        });
    
        $(document).bind('pageshow', function (event) {
            var hash = $(event.target).attr('id');
            bindEvents[hash]();
        });
    </script>
    

    在页面中:

    1.索引:

    <script type="text/javascript">
    var hashedIndex = '@Request.RawUrl.GetHashCode()';
    if (!bindEvents.hasOwnProperty(hashedIndex)) {
        bindEvents[hashedIndex] = function() {
            $(window).bind('click.' + hashedIndex, function() {
                console.log('index');
            });
        };
    };
    </script>
    

    2.关于:

    <script type="text/javascript">
    var hashedAbout = '@Request.RawUrl.GetHashCode()';
    if (!bindEvents.hasOwnProperty(hashedAbout)){
        bindEvents[hashedAbout] = function () {
            $(window).bind('click.' + hashedAbout, function() {
                console.log('about');
            });
        };
    };
    </script>
    

    如果需要,与其他页面类似。

    在一般情况下,我同意 Gajotres:最好将事件绑定到一些内部容器以避免此类问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多