gpt4 book ai didi

c# - ASP.NET MVC3 jQuery 移动页面的 Ajax 代码绑定(bind)使用 PageInit 事件

转载 作者:行者123 更新时间:2023-11-30 18:37:54 25 4
gpt4 key购买 nike

我们正在使用 ASP.NET MVC3 + JqueryMobile RC1 编写 JQueryMobile 应用程序。很少有页面有自己的 Ajax 方法,我们使用 jQuery 代码 ($.getJSON()) 方法调用这些方法。

为了在 Ajax 调用中调用这些,我们在 jquery-mobile 的“pageinit”事件中执行点击事件绑定(bind),如此处所述(http://jquerymobile.com/demos/1.0rc1/docs/api/events.html)。但是,调用绑定(bind)到 pageinit 的方法会在每次访问页面时增加 +1。例如如果我使用后退按钮或任何其他链接再次访问我的页面,请再次访问它,调用两次 pageinit 方法,并且在 pageinit 中编写的任何代码都执行两次......这些随着每次访问页面而不断增加。

我们应该使用哪个事件来绑定(bind)事件。它应该只在页面加载时调用一次吗?

编辑:-我们需要 JQM 的默认 AJAX 行为,并且我们将 AjaxEnabled 保持为 true。

示例源代码(您可以通过创建新的 MVC3 APP 并将以下三个 .cshtml 替换为给定代码来重现此问题:-

我的 _Layout.cshtml:-

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc1/jquery.mobile-1.0rc1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.0rc1/jquery.mobile-1.0rc1.min.js"></script>
@RenderSection("HeaderScripts", required: false)
</head>
<body>
<div data-role="page" id="@ViewBag.DivTitle">
<div data-role="header">
<h1>
@ViewBag.Title
</h1>
<a href="/Home/About" data-role="Button" data-icon="info" data-iconpos="notext">About</a>
<a href="/Home/Index" data-role="Button" data-icon="home" data-iconpos="notext">Home</a>
</div>

<div data-role="content" id="DivContent">
@RenderBody()
@RenderSection("BodyScriptsSection", required: false)
</div>

<div data-role="footer" data-position="fixed">
@RenderSection("MobileFooter", required: false)
</div>
</div>
</body>
</html>

示例索引.cshtml

@{
ViewBag.Title = "Home Page";
ViewBag.DivTitle = "HomeIndex";
}

@section BodyScriptsSection {
<script type="text/javascript">
$("#@ViewBag.DivTitle").live("pageshow", function () {
alert ("PageShow Called - HomeIndex");
});

</script>

示例 AboutUS.cshtml

@{
ViewBag.Title = "About Us";
ViewBag.DivTitle = "AboutUS";

}

@section BodyScriptsSection {
<script type="text/javascript">
$("#@ViewBag.DivTitle").live("pageshow", function () {
alert("PageShow Called - AboutUS");
});

</script>

最佳答案

你为什么不在导航离开时杀死你的处理程序,像这样:

$("#@ViewBag.DivTitle").live("pagehide", function() {
$("#@ViewBag.DivTitle").die("pageshow");
}

关于c# - ASP.NET MVC3 jQuery 移动页面的 Ajax 代码绑定(bind)使用 PageInit 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7724959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com