原文地址:https://www.blog-china.cn/liuzaiqingshan/home/37/1497495953226
大概说下需求: 当点击不同的TAB选项卡,我希望通过AJAX加载不同的html页面或者请求,而不是事先将DIV都加载到 这个页面中。
废话不多说,直接 上代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title> CDCN - 码上中国 www.blog-china.cn</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords"
content="Bootstrap blog , queryBuilder 博客,jquery queryBuildder , queryBuilder 博客,queryBuilder 论坛,queryBuilder 技术,Bootstrap 博客 "/>
<link rel="stylesheet" href="../../bootstrap-3.3.5-dist/css/bootstrap.min.css" type="text/css">
<script type="text/javascript" src="../../js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="../../bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
//准备tabs数据
var tabsData = [{
"id" : "test-paper",
"url" : "IE8.html"
},{
"id" : "favorite",
"url" : "erweima.html"
},{
"id" : "about",
"url" : "document_index.html"
},{
"id" : "user-info-page",
"url" : "my_resosurce.html"
}];
//遍历json数组,循环添加a标签click事件:
$(tabsData).each(function(){
//console.info(this.id + "--->" + this.url);
$("a[href='#"+this.id+"']").bind('click',{
id : this.id,
url : this.url
},tabsHandler);
});
});
function tabsHandler(event) {
var data = event.data;
showTabs(data.id,data.url);
return false; //阻止默认a标签响应
}
/**
* 激活tab选项卡并使用ajax异步加载内容
* @param {Object} tabsId
* @param {Object} url
*/
function showTabs(tabsId,url) {
$("a[href='#"+tabsId+"']").tab('show');
var $tabContent = $('#'+tabsId);
if($tabContent.length < 100) {
$tabContent.load(url);
//console.info(tabsId + ' load done!');
}
}
//依次为每个tab导航a标签添加单击事件
$('a[href="#test-paper"]').click(function(e) {
showTabs('test-paper','pages/test-paper.jsp');
e.preventDefault();
});
</script>
<!-- cropper end-->
</head>
<body>
<!-- content -->
<div class="container bs-docs-container">
<div class="row">
<div class="col-md-3" role="complementary">
<ul id="myTab" class="nav nav-pills nav-stacked">
<li class="active">
<a href="#home" data-toggle="tab" name="menu-ctrl">
<span class="glyphicon glyphicon-home"> </span> 主页
<span class="sr-only">(current)</span>
</a>
</li>
<li>
<a href="#test-paper">
<span class="glyphicon glyphicon-list-alt"> </span> 试卷库
</a>
</li>
<li>
<a href="#favorite">
<span class="glyphicon glyphicon-bookmark"> </span> 我的收藏
</a>
</li>
<li>
<a href="#about">
<span class="glyphicon glyphicon-info-sign"> </span> 关于
</a>
</li>
</ul>
</div>
<div class="col-md-9" role="main">
<div id="myTabContent" class="tab-content">
<!-- 试卷库页面 -->
<div class="tab-pane fade" id="test-paper"></div>
<!-- 收藏页面 -->
<div class="tab-pane fade" id="favorite"></div>
<!-- 关于页面 -->
<div class="tab-pane fade" id="about"></div>
<!-- 用户信息页面 -->
<div class="tab-pane fade" id="user-info-page"></div>
</div>
</div>
</div>
</div>
</body>
</html>
效果如下: