我在HTML下方有多个<h1>
,并在每个<h1>
一个段落元素之后。我想一次显示一个<p>
。
HTML
<h1>Heading One</h1>
<p class="answ 1">This is first paragraph.</p>
<h1>Heading One</h1>
<p class="answ 2">This is first paragraph.</p>
<h1>Heading One</h1>
<p class="answ 3">This is first paragraph.</p>
的JavaScript
(function(){
var heading = document.getElementsByTagName('h1');
para = document.getElementsByTagName('p')[0];
buttons = document.getElementsByTagName('a');
var evtDelegation = function(evt){
var target = evtUtility.getTarget(evt);
if(target.nodeName.toLowerCase() === 'h1'){
evtUtility.nextSiblings(target).style.display = 'block';
};
};
evtUtility.addEvent(document, 'click', evtDelegation);
})();
工作示例:Demo
答案 0 :(得分:1)
在打开新标签之前关闭其他p
标签:
var heading = document.getElementsByTagName('h1');
var para = document.getElementsByTagName('p')[0];
var buttons = document.getElementsByTagName('a');
var paras = document.getElementsByTagName('p');
var evtDelegation = function(evt){
var target = evtUtility.getTarget(evt);
if(target.nodeName.toLowerCase() === 'h1'){
for(var i = 0; i < paras.length; i++){
paras[i].style.display = "none";
}
evtUtility.nextSiblings(target).style.display = 'block';
};
};
JS小提琴: http://jsfiddle.net/bwNu8/2/
答案 1 :(得分:0)
if(target.nodeName.toLowerCase() === 'h1'){
/* get all "p" elements*/
var ps=document.getElementsByTagName("p");
/* traverse through those elements */
for(var i=0;i<ps.length;i++){
/* if any of it has class "answ" hide it*/
if(ps[i].getAttribute("class").indexOf("answ")!=-1)
ps[i].style.display='none';
}
evtUtility.nextSiblings(target).style.display = 'block';
};
答案 2 :(得分:0)
您可以存储对先前打开的段落的引用,并在显示新段落之前将其隐藏。如果你有很多段落,这样做的好处就是更快。
// My function to open and close the p tag
var para = null
var evtDelegation = function(evt){
var target = evtUtility.getTarget(evt);
if(target.nodeName.toLowerCase() === 'h1'){
if(para !== null) {
para.style.display = 'none';
}
para = evtUtility.nextSiblings(target);
para.style.display = 'block';
};
};
evtUtility.addEvent(document, 'click', evtDelegation);