ajax效果:ajax标签tabs效果

很多朋友对于标签应用的效果不是很清楚,尤其是AJAX标签的应用,知之更少。

很久以前在国外网站上看过一个AJAX标签的代码,很不错,很简单,比较容易学会调用,应该对初学者会很有帮助。

话不多讲,先上代码,再来解释!
JS代码: //Change Log:
//* Updated: July 11th, 07: Fixed bug with persistence not working. Doh.
//* Updated: July 9th, 07: Added session only persistence to tabs (set "enabletabpersistence" var below). Only .js file changed.
//* Updated Nov 8th, 06. Ability to select a tab dynamically, by calling a method (ie: via a link). Only .js file changed.

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadstatustext="<img src='ajaxtabs/loading.gif' /> Requesting content..."
var enabletabpersistence=1 //enable tab persistence via session only cookies, so selected tab is remembered (1=yes, 0=no)?

////NO NEED TO EDIT BELOW////////////////////////
var loadedobjects=""
var defaultc Object()
var bustcacheparameter=""

function ajaxpage(url, containerid, targetobj){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
var ullist=targetobj.parentNode.parentNode.getElementsByTagName("li")
for (var i=0; i<ullist.length; i++)
ullist.className="" //deselect all tabs
targetobj.parentNode.className="selected" //highlight currently clicked on tab
if (url.indexOf("#default")!=-1){ //if simply show default content within container (verus fetch it via ajax)
document.getElementById(containerid).innerHTML=defaultcontentarray[containerid]
return
}
document.getElementById(containerid).innerHTML=loadstatustext
page_request.(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(revattribute){
if (revattribute!=null && revattribute!=""){ //if "rev" attribute is defined (load external .js or .css files)
var objectlist=revattribute.split(/\s*,\s*/) //split the files and store as array
for (var i=0; i<objectlist.length; i++){
var file=objectlist
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
}

function expandtab(tabcontentid, tabnumber){ //interface for selecting a tab (plus expand corresponding content)
var thetab=document.getElementById(tabcontentid).getElementsByTagName("a")[tabnumber]
if (thetab.getAttribute("rel")){
ajaxpage(thetab.getAttribute("href"), thetab.getAttribute("rel"), thetab)
loadobjs(thetab.getAttribute("rev"))
}
}

function savedefaultcontent(contentid){// save default ajax tab content
if (typeof defaultcontentarray[contentid]=="undefined") //if default content hasn't already been saved
defaultcontentarray[contentid]=document.getElementById(contentid).innerHTML
}

function startajaxtabs(){
for (var i=0; i<arguments.length; i++){ //loop through passed UL ids
var ulobj=document.getElementById(arguments)
var ulist=ulobj.getElementsByTagName("li") //array containing the LI elements within UL
var persisttabindex=(enabletabpersistence==1)? parseInt(getCookie(arguments)) : "" //get index of persisted tab (if applicable)
var isvalidpersist=(persisttabindex<ulist.length)? true : false //check if persisted tab index falls within range of defined tabs
for (var x=0; x<ulist.length; x++){ //loop through each LI element
var ulistlink=ulist[x].getElementsByTagName("a")[0]
ulistlink.index=x
if (ulistlink.getAttribute("rel")){
var modifiedurl=ulistlink.getAttribute("href").replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/")
ulistlink.setAttribute("href", modifiedurl) //replace URL's root domain with dynamic root domain, for ajax security sake
savedefaultcontent(ulistlink.getAttribute("rel")) //save default ajax tab content
ulistlink.(){
ajaxpage(this.getAttribute("href"), this.getAttribute("rel"), this)
loadobjs(this.getAttribute("rev"))
saveselectedtabindex(this.parentNode.parentNode.id, this.index)
return false
}
if ((enabletabpersistence==1 && persisttabindex<ulist.length && x==persisttabindex) || (enabletabpersistence==0 && ulist[x].className=="selected")){
ajaxpage(ulistlink.getAttribute("href"), ulistlink.getAttribute("rel"), ulistlink) //auto load currenly selected tab content
loadobjs(ulistlink.getAttribute("rev")) //auto load any accompanying .js and .css files
}
}
}
}
}

////////////Persistence related functions//////////////////////////

function saveselectedtabindex(ulid, index){ //remember currently selected tab (based on order relative to other tabs)
if (enabletabpersistence==1) //if persistence feature turned on
setCookie(ulid, index)
}

function getCookie(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return ""
}

function setCookie(name, value){
document.cookie = name+"="+value //cookie value is domain wide (path=/)
}

HTML代码: <ul id="maintab" class="shadetabs">
<li class="selected"><a href="#default" rel="ajaxcontentarea">Intro</a></li>
<li><a href="external.htm" rel="ajaxcontentarea">Bird</a></li>
<li><a href="external2.htm" rel="ajaxcontentarea">Dog</a></li>
<li><a href="external3.htm" rel="ajaxcontentarea">Cat</a></li>
<li><a href="external4.htm" rel="ajaxcontentarea" rev="content.css, content.js">Sea Otter</a></li>
</ul>

<div id="ajaxcontentarea" class="contentstyle">
<p>This is some default tab content, embedded directly inside this space and not via Ajax. It can be shown when no tabs are automatically selected, or associated with a certain tab, in this case, the first tab.</p>
</div>

<script type="text/javascript">
//Start Ajax tabs script for UL with id="maintab" Separate multiple ids each with a comma.
startajaxtabs("maintab")
</script>

下面解释:
ul的id="maintab"是必需的,因为后面AJAX效果调用要根据这个ID来查找对象,所以后面还有一句startajaxtabs("maintab"),这里面就是调用的UL的ID。
li的class="selected"代表当前选中状态。selected也是必需的,最好不要随便改其它名字,如果要改的话,相应JS里面的设置也要改。
A标签里面的href属性代表要加载的HTML地址(#default代表容器默认的内容。),rel属性代表加载到的HTML内容显示在对象ID为该属性值的容器里。rev属性代表把该对象应用到HTML上并显示。
同时该JS还提供了一个额外的方法让我们操纵标签:expandtab(tabcontentid, tabnumber)

<A href="javascript:expandtab(maintab, 2)">显示maintab的第3个标签的内容</a>

因为数组都是从0开始统计,所以2就代表第3个。

多个AJAX标签对象只需要在startajaxtabs("maintab")后面加上相应的UL 的ID即可。

例如:
<ul id="maintab" class="shadetabs">
<li><a href="external.htm" rel="ajaxcontentarea">Bird</a></li>
<li><a href="external2.htm" rel="ajaxcontentarea">Dog</a></li>

</ul>

<div id="ajaxcontentarea" class="contentstyle">
<p>Default Content...</p>
</div>

<ul id="newstab" class="shadetabs">
<li><a href="local.htm" rel="newscontentarea">Local</a></li>
<li><a href="world.htm" rel="newscontentarea">World</a></li>

</ul>

<div id="newscontentarea" class="contentstyle">
<p>Default Content...</p>
</div>

<script type="text/javascript">
startajaxtabs("maintab", "newstab")
</script>

代码示例下载地址:http://minado008.host.2wcn.com/demo/ajax
Tags:  phpajax ajax教程 ajax登陆效果 ajax效果

延伸阅读

最新评论

发表评论