我对
jquery mobile有点问题.总是我的页面被称为此功能运行.
$(document).bind('pagechange',function () { // peforms ajax operations });
问题是每次查看我的页面时都会增加调用ajax的次数…例如:如果页面被查看5次,下次将执行相同的ajax请求6次.
我正在使用asp.Net MVC 4.
完整代码:
@{ //ViewBag.Title = "Consulta"; Layout = "~/Views/Shared/_LayoutMenu.cshtml"; } <div class="ui-body ui-body-b" id="test"> (...) some html code (...) </div> <script> $(document).bind('pagechange',function () { $('#info').css('visibility','hidden'); $('#name').keypress(function (e) { if (e.keyCode == 13) { var code = $(this)[0].value; $.ajax({ url: '/Consulta/ObterDadospulseira',data: $(this).serialize(),success: function (data) { $('#info').css('visibility','visible'); var info = $('#info')[0]; $('#info [id=gridCod]').html(data[0].cod); $('#info [id=gridName]').html(data[0].nome); },complete: function () { },error: function () { alert('error!'); } }); $(this)[0].value = ''; } }); $('#name').focus(); });
解决方法
通常这是因为您在另一个事件处理程序中绑定事件处理程序.例如,如果您在pageshow事件处理程序中绑定了一个pagechange事件处理程序.
此外,如果要绑定到特定页面的页面事件,则只需绑定到data-role =“page”元素:
$(document).delegate('#my-page-id','pageshow',function () { //Now `this` refers to the `#my-page-id` element });
更新
我刚刚看到你的更新答案与额外的代码,你的问题是你绑定另一个事件处理程序内的事件处理程序.基本上每次触发pagechange事件时,都会将新的事件处理程序绑定到#name元素.
试试这个:
$(document).delegate('#name','keypress',function () { if (e.keyCode == 13) { var code = this.value; $.ajax({ url: '/Consulta/ObterDadospulseira',success: function (data) { $('#info').css('visibility','visible'); var info = $('#info')[0]; $('#info [id=gridCod]').html(data[0].cod); $('#info [id=gridName]').html(data[0].nome); },error: function () { alert('error!'); } }); this.value = ''; } }).bind('pagechange','hidden'); $('#name').focus(); });
这使用事件委托将事件处理程序绑定到#name元素,这样事件处理程序将一次绑定一次.
.delegate()的文档:http://api.jquery.com/delegate