我有这些语法来刷新浏览器后显示随机文本和图像。一切正常。请看一下。随机图像,刷新后随机文本显示
的JavaScript
var quotes=new Array();
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementsByTagName('img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
HTML
<div id="quote"></div>
<div>
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
CSS
.image {
display: none;
}
但后来,我增加了许多更<img scr.../>
标签(未涉及到这个JavaScript的目的)在页面的不同位置,然后随机图像没有出现。
我尝试了一种不同的方法,将document.getElementById更改为document.getElementByClassName,如下面的语法,它不起作用。
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementByClass('image')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
然后,我尝试在每个<img..>
标签添加一个id =“imgShow”
<div id="quote"></div>
<div>
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=1" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=2" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=3" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
而不是document.getElementsByTagName
,我如下更改为document.getElementById
,但随机图像不显示,要么。
任何想法?
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('imgShow')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
我也尝试通过添加ID父<div>
区分随机<img src>
标签与页面内的其他<img src>
标签,然后试图调用只有<img>
该ID里面,但没有成功。
HTML
<div id="quote"></div>
<div id="RefreshImg">
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
的JavaScript
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('RefreshImg img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
你有什么想法?
类的名字似乎是要走的路。请注意,您提供的代码将'getElementByClass'放置在我认为您想要的地方'getElementsByClassName' – chiliNUT
顺便提一下,每个元素都应该具有唯一的ID。 – ElDoRado1239
如果你像'['text1','text2','text3','text4']创建你的数组,你可以节省空间。 – elclanrs