document.getElementByClassName不会工作

时间:2017-09-01 19:11:43

标签: javascript html css

我在JavaScript中将按钮样式从id更改为class 风格显然在按钮上显示,但它不起作用。 (是的,我确实检查了stackoverflow和网络的解决方案 这是代码:

var currImage = 0;
window.onload = () => {
    const factsArr = [
    { image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"<a href='http://news.nationalgeographic.com/news/2010/03/100315-half-male-half-female-chickens/' style='text-decoration:none;color:#FFFFFF;' target='_blank'>know more</a>"},
    { image:'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif', source:"<a href='https://broadly.vice.com/en_us/article/mbqjap/witches-allegedly-stole-penises-and-kept-them-as-pets-in-the-middle-ages'style='text-decoration:none;color:#FFFFFF;'target='_blank'>know more</a>"},
  { image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif',      source:"<a href='http://www.guinnessworldrecords.com/world-records/most-expensive-pizza' style='text-decoration:none;color:#FFFFFF;'target='_blank'>know more</a>"},
    ];

 const swtch = () => {
    document.getElementById('image').setAttribute('src', factsArr[currImage].image);
    document.getElementById('source').innerHTML=factsArr[currImage].source;
    currImage++;
    if (currImage == factsArr.length)
        currImage = 0;
    console.log(currImage);
};
document.getElementByClassName('generate-btn').addEventListener('click', swtch);
document.getElementById('source').addEventListener('click', swtch);
}
.generate-btn{
height:16%;
margin:auto;
background-color: #8a2be2;
color:white;
font-family: 'Open Sans',sans-serif;
font-size:24px;
display: inline-block;
padding:32px 16px;
border-radius: 2%;
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
text-align: center;
cursor: pointer;
position: absolute;
left: 40%;
top: 100%;
width: 20%;
}
@media screen and (width: 600px) {
    .generate-btn{
        width:100%;
        height:auto;
        font-size:100%;
    }
}
<button class="generate-btn">Amazing Fact Button</button>
<div id="source"></div>
<img id="image" />

2 个答案:

答案 0 :(得分:3)

该函数名为getElementsByClassName,它返回具有该类的元素列表。

为了将事件附加到相关元素,您可以使用第一个元素并使用:

document.getElementsByClassName('generate-btn')[0].addEventListener('click', swtch);

或者逐个循环,并附上相关事件:

elements = document.getElementsByClassName('generate-btn');
Array.prototype.forEach.call(elements, function(el) {
    el.addEventListener('click', swtch);
});

答案 1 :(得分:1)

如果页面上只有一个此类,则可以使用querySelector代替getElementsByClassName。这将为您提供给定CSS样式选择器的第一个匹配。

document.querySelector('.generate-btn').addEventListener('click', swtch);

如果有多个,请使用querySelectorAll循环。

无论哪种方式,您都可以获得更好的整体浏览器支持,因为IE8支持querySelector方法,但不支持getElementsByClassName