一、问题分析
对于后台系统,相比大家都有所印象,知道其中的布局结构,如图:
在这种布局中我们需要将header,sidebar,footer分开,而且对于中间部分的content内容需要动态变化,即根据不同菜单定位到不同页面,而整体布局不会变化
这种布局结构对于单纯的HTML不具备这种嵌入各部分内容的能力,所以就需要我们自己来寻找或者解决这种问题,由于jquery的兼容性和使用广度比较不错,这里
使用jquery的load方法来处理这种页面布局框架。
二、load方法详解
1.定义 $().load(,,);
必需的 URL 参数规定您希望加载的 URL。
可选的 data 参数规定与请求一同发送的查询字符串键/值对集合。
可选的 callback 参数是 load() 方法完成后所执行的函数名称。
2.示例
也可以把 jQuery 选择器添加到 URL 参数。
下面的例子把 "demo_test.txt" 文件中 id="p1" 的元素的内容,加载到指定的
元素中:
$("#p1").load("demo_test.txt #p1");
可选的 callback 参数规定当 load() 方法完成后所要允许的回调函数。回调函数可以设置不同的
$("#p1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){ if(statusTxt=="success") alert("外部内容加载成功!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); });
三、布局框架load的使用
1.问题
网上很多人在使用load方法加载动态页面的时候遇到一个普遍的问题,就是在被加载页面中的JavaScript代码失效,这是因为load加载的外部文件会把Script部分删除掉,所以被加载页面中调用该页面的JavaScript的时候就会出现xxxfunction未定义。
2.解决
对于header,sidebar,footer这种只包含静态HTML代码的部分直接使用load加载
对应中间content变化的内容,一般都会包含对应的JavaScript代码,使用自定义的load方法(如下代码),在使用jquery.load()方法加载对应的内容的同时,使用load的回调方法处理JavaScript的加载,将被加载页面的JavaScript代码加载到布局页面的
中这样每次load()的时候content的内容都会被覆盖,所以也不必担心重复加载的问题。这样就完美解决被加载页面js失效的问题。具体代码如下所示:四、代码示例
布局页面:
nbsp;html> <meta> <meta> <title></title> <!-- Tell the browser to be responsive to screen width --> <meta> <!-- Bootstrap 3.3.6 --> <link> <p> </p><p> </p> <!-- Left side column. contains the logo and sidebar --> <p> </p> <!-- Content Wrapper. Contains page content --> <p> <!-- Content Header (Page header) --> </p> <!-- /.content-wrapper --> <p> </p> <!-- Add the sidebar's background. This p must be placed immediately after the control sidebar --> <p></p> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script></script> <!-- Bootstrap 3.3.6 --> <script></script> <!--左侧菜单--> <script></script> <script></script> <script></script> <script> //加载页面布局的header,sidebar,footer的内容 $("#header").load("inc/header.html"); $("#sidebar").load("inc/sidebar.html"); $("#footer").load("inc/footer.html"); /* *加载变换内容,主要url参数为dom对象,并且该dom中的url放在href中, *调用方式如:<span onclick="javascript:load(this);" href="/backstage/website/test.html">测试 *注意:1.该dom对象最好不要用a标签,因为点击a标签会进入href指定的页面 * 2.要加载的内容要用 id="content" 标注,因为load中指明了加载页面中指定的id为content下的内容 * 3.对应页面的JavaScript写在content下 */ function load(url, data){ //alert($(url).attr("href")); $.ajaxSetup({cache: false }); $("#content").load($(url).attr("href")+ " #content ", data, function(result){ //alert(result); //将被加载页的JavaScript加载到本页执行 $result = $(result); $result.find("script").appendTo('#content'); }); }</script>
被加载页面:
<p> </p><p>测试二</p> <span>测试</span> <a>测试</a> <script> function test(){ alert("测试二页面"); } </script> <script> function test2(){ alert("ceshi"); } </script>
效果截图:
以上就是使用jquery的load方法设计动态加载,并解决被加载页面JavaScript失效问题的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号