我有 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"
页面时 - 此处理程序仍处于活动状态。
有没有办法仅在适当的页面处于活动状态时保留处理程序?
将这种事件绑定与 jQM 一起使用:
$('#page').bind('click', function(e) {
});
对于较新版本的 jQuery,请使用 .on( 和 .off( 来绑定/取消绑定事件。 $('#page') 是你的页面。
这:
$(window).click()
会将其绑定到窗口,因为jQM页面是每次都会触发的单个窗口事件。您还需要担心多个事件绑定,在这里您可以找到有关此问题的更多信息。
我对这个问题做了一些小研究,但没有找到任何合适的问题。因此,我已经为带有窗口事件的描述用例实现了解决方案。这令人毛骨悚然,但有效。
在布局中:
1.Pagediv 声明:
<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 的观点:最好将事件绑定到一些内部容器以避免此类问题。