function new1()
{ var news = ["1","2","3","4"];
for (var i = 0; i<news.length; i++)
{
var s =document.getElementById("news"+news[i]).style.display = "none";
}
}
在此先感谢,如果需要,我可以提供xhtml,它只是几个名为news1,new2的div,我主要担心的是错误是阻止其他一些脚本工作。 提前谢谢=]
<a onclick="show1()" href="#"><h3>Spice Girls premiere new song</h3></a><div id="news1">
<p class="news" > <em>Headlines (Friendship Never Ends)</em> is the first new single from the reformed girl band since 2000 and is the official Children In Need track for 2007.</p>
<p class="news">Geri Halliwell, Victoria Beckham, Melanie Brown, Melanie Chisholm and Emma Bunton have regrouped to promote a new Spice Girls' greatest hits album and an upcoming world tour. <a href="#">more ...</a></p></div>
</div>
<div id="story2">
<a onclick="show2()" href="#"><h3>Jay-Z defends Nas album title</h3></a><div id="news2">
<p class="news">Hip-hop mogul Jay-Z has defended Nas' decision to name his new album <span>N**ger</span>, but insists the naming of the record is "misguided".</p>
<p class="news">Jay-Z - real name Shawn Carter - is releasing the LP under his label Island Def Jam Music Group, but admits he is not fond of its title. <a href="#">more ...</a></p></div>
</div>
<div id="story3">
<a onclick="show3()" href="#"><h3>Winehouse defends MTV EMAs performance</h3></a><div id="new3">
<p class="news" id="news3">Amy Winehouse has defended her performance at Thursday's MTV European Music Awards - citing exhaustion for her bizarre behaviour. <a href="#">more ...</a></p></div>
答案 0 :(得分:1)
循环很好,索引0,1和2中的元素,但查看最后一个元素将是id news4 ,JS调用将抛出错误因为没有带有该id的DOM元素。
因此,删除ids数组中的最后一个条目:
function new1() {
var news = ["1","2","3","4"];
for (var i = 0; i<news.length; i++)
{
var newsElement = document.getElementById("news"+news[i]);
if (newsElement != null)
{
newsElement.style.display = "none";
}
}
}
答案 1 :(得分:0)
使用jQuery。漂亮,简单和跨浏览器:
function new1()
{
var news = ["1","2","3","4"];
for (var i = 0; i<news.length; i++)
{
$('#news' + news[i]).hide();
}
}