将图像的“ src”属性更改为另一个图像文件?

时间:2019-06-01 15:29:47

标签: javascript html

这部分工作是指示我将星型图像集合的src属性更改为另一个图像文件。

我尝试了 removeAttribute() setAttribute()的多种组合,但是没有运气。我可能在这里想错了方向。

function lightStars () {
   var starNumber = e.target.alt;
   var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
   stars.setAttribute("src", "bw_star2.png");
}
} 

HTML代码:

<label id="ratingLabel" for="rating">Rate this title
           <span id="stars">
           <img src="bw_star.png" alt="1" />
           <img src="bw_star.png" alt="2" />
           <img src="bw_star.png" alt="3" />
           <img src="bw_star.png" alt="4" />
           <img src="bw_star.png" alt="5" /></span>
           <input type="text" name="rating" id="rating" readonly value="" />
</label>

此功能的目的是当用户将鼠标指针移到星图上时为星上色,以反映用户对该书的评价。

我希望我能正确解释。

4 个答案:

答案 0 :(得分:0)

如果我正确地理解了您的代码,我认为您只是错过了访问每个star数组位置的机会:

function lightStars () {
    var starNumber = e.target.alt;
    var stars = document.querySelectorAll("span#stars img");
    for (var i = 0; i < starNumber; i++) {
        stars[i].setAttribute("src", "bw_star2.png");
    }
}

答案 1 :(得分:0)

function lightStars () {
   var starNumber = parseint(e.target.alt);
   var stars = document.querySelectorAll("span#stars img");
   for (var i = 0; i < starNumber; i++) {
       stars.setAttribute("src", "bw_star2.png");
   }
}

答案 2 :(得分:0)

document.querySelectorAll()返回一个StaticNodeList,节点可以通过它从索引0开始的索引号访问,而不是从元素本身开始,因此您不能在每个元素上设置属性,而是使用{{1 }}方法。

forEach()

答案 3 :(得分:0)

我使用了glyphicons而不是img。 querySelectorAll返回元素列表。因此,要更改其属性值,您需要对其进行迭代。

const imgs = document.querySelectorAll('span');

imgs.forEach((img) => {
    img.addEventListener('mouseover', function()  {
      const ratings = this.getAttribute('data-rating');
      for(let i = 0; i < ratings; i++) {
          imgs[i].setAttribute('class', 'glyphicon glyphicon-star');
      }

      for(let j = ratings; j < imgs.length; j++) {
          imgs[j].setAttribute('class', 'glyphicon glyphicon-star-empty');
      }
  });
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<label id="ratingLabel" for="rating">Rate this title
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="1"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="2"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="3"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="4"></span>
        <span class="glyphicon glyphicon-star-empty" aria-hidden="true" data-rating="5"></span>
        <input type="text" name="rating" id="rating" readonly value="" />
     </label>

相关问题