I am currently using the following code on a website to allow some div's to be populated with content via ajax when a li开发者_如何转开发nk is clicked, as well as hidden again if clicked a second time.
The javascript function that does this is (stripped of irrelevant code):
function showNews(id){
if(CONDITION){
ajax(); //Not actual code, original code just grabs content via ajax and puts it into an existing empty div using innerHTML.
}
else if (CONDITION) {
document.getElementById('div'+id).innerHTML = ''; // Empties div again, in effect hiding it from view.
}
}
This currently works fine, as when each link is clicked the corresponding DIV fills with content, and when clicked again the content disappears. However, I can open as many of these div's as I want at the same time. I want it to work so that when a new div is populated the rest are emptied.
All of the div's have an ID like this: id="div#" where the # is replaced with a unique ID number.
So I need to do something like this:
function showNews(id){
if(CONDITION){
ajax(); //Not actual code, original code just grabs content via ajax and puts it into an existing empty div using innerHTML.
**FOR ALL DIVS THAT HAVE AN ID THAT STARTS WITH 'div', BUT DOES NOT MATCH CURRENT ID VARIABLE, SET innerHTML = ''**
}
... code removed from original ...
}
I hope this makes sense.
document.getElementsByTagName('div')
is an array (a node list, actually) of all divs.
You can check their IDs with .id
.
Try this:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
if( (divs[i].id.substr(0,3) == 'div') && (divs[i].id != ('div' + ID)) )
divs[i].innerHTML = '';
divs[i].id.substr(0,3) == 'div'
checks if the div's id
is divSomething
.
divs[i].id != ('div' + ID)
makes an exception for divID
.
Maybe you could give each div the same name (because names, unlike Ids, do not have to be unique) then use document.getElementsByName to find & clear them prior to populating the current div.
精彩评论