当前位置:编程学习 > JAVA >>

jQuery Mobile 加载对话框页面时同名javascript函数冲突、覆盖问题

jQuery Mobile 加载对话框页面时 javascript 函数冲突、覆盖问题
版本:jQuery Mobile 1.1.0/1.2.0
问题描述:有两个页面 main.cshtml 和 dialog.cshtml 。两个页面都是基于.NET MVC4的,都使用了默认模板 _layout.cshtml。
在main.cshtm页面上,使用javascript加载数据列表,点击链接后,以对话框形式弹出dialog.cshtml页面,dialog.cshtml页面上也采用javascript进行数据加载。
弹出对话框后关闭对话框,发现main.cshtml上的javascript函数不可用了!
经过实验发现,这是由于jQuery Mobile使用ajax方式加载页面,导致两个页面的javascript同名函数产生了冲突!
 
.NET MVC 4的_layout.cshtml 模板内容如下:
[html]  
<!DOCTYPE html>  
<html lang="zh">  
    <head>  
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
        <meta charset="utf-8" />  
        <title>@ViewBag.Title</title>  
        <meta name="viewport" content="width=device-width" />  
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
        @Styles.Render("~/Content/mobileCss", "~/Content/css")  
        @Scripts.Render("~/bundles/modernizr")  
    </head>  
<body>  
       <div data-role="page" data-theme="b">  
        <div data-role="header">  
            @if (IsSectionDefined("Header"))   
            {  
                @RenderSection("Header")  
            }   
            else  
            {  
                <h1>@ViewBag.Title</h1>  
            }  
        </div>  
        <div data-role="content">  
            @RenderBody()  
        </div>  
    </div>  
    @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")  
    @RenderSection("scripts", required: false)  
</body>  
</html>  
 
当我们新建页面,并在页面中写<script>...</script>和html标签时,实际上是写在了模板页面如下的div中:
<div data-role="content">
            @RenderBody()
</div>
当jQuery Mobile使用ajax方式加载其它页面时,实际上只是加载了该页面的 <div data-role="content">....</div>部分。www.zzzyk.com
如果两个页面的<div data-role="content">....</div>中存在同名的javascript函数,则会导致冲突!关闭对话框页面后,mian.cshtml 页面的 javascript 函数会变成 dialog.cshtml 的同名javascript函数!
jQuery Mobile 的ajax加载原理如下图所示:
总结如下:
当使用jQuery Mobile进行开发时,如果多个相互跳转的页面都有javascript函数,则应该将每个页面的Javascript函数以不同的名字命名,避免导致同名函数的覆盖冲突问题。
 
补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,