简体   繁体   English

如何从JavaScript更改没有类/ ID的图像的src

[英]How to change the src of images which has no class/ID from JavaScript

I would like to change the source of the img from JavaScript by using Ajax. 我想使用Ajax从JavaScript更改img的来源。 And img tag does not have any IDs or classes, and I cannot figure out how to select the img and how to change the src . 并且img标签没有任何ID或类,并且我无法弄清楚如何选择img以及如何更改src How can I do that? 我怎样才能做到这一点? I put part of my HTML (it is provided, and so I cannot modify) and part of my JavaScript. 我放入了一部分HTML(已提供它,因此无法修改)和一部分JavaScript。 Thanks. 谢谢。

HTML: HTML:

<div class="moves">
          <button>
            <span class="move">Move Name Here</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">Move Name Here</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">Move Name Here</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
          <button>
            <span class="move">Move Name Here</span> <span class="dp"></span>
            <img src="icons/fighting.jpg" alt="Pokemon move" />
          </button>
 </div>

Javascript: 使用Javascript:

        var moveArr = data.moves;
        var moves = document.getElementsByClassName("move");
        for(var x=0; x < data.moves.length; x++){
            moves[x].innerHTML = moveArr[x].name;
            img[x].src = "icons\/" + moveArr[x].type + ".jpg"; // I cannot write this part correctly.
        }

Yeah, you don't have a reference to the image that you are trying to change the src of. 是的,您没有对要更改其src的图像的引用。 I would do: 我会做:

var moveArr = data.moves;
var moves = document.getElementsByClassName("move");
for(var x=0; x < data.moves.length; x++){
    moves[x].innerHTML = moveArr[x].name;
    var img = moves[x].parentNode.getElementsByTagName('img')[0];
    img.src = "icons\/" + moveArr[x].type + ".jpg";
}

If the layout of your page changes you might have to alter this code. 如果页面布局更改,则可能必须更改此代码。 Should work for what you have now, though. 不过,应该可以满足您现在的需求。

If each span is succeeded by an img (as it appears to be from the code you've posted) so there's the same number of .move items and images -- and they match up -- then you can use the DOM images collection to target each image's src , like so: 如果每个span都由一个img (看起来像是您发布的代码)后接,那么.move项和图像的数量相同-并且它们匹配-那么您可以使用DOM images集合来定位每个图像的src ,如下所示:

    var moveArr = data.moves;
    var moves = document.getElementsByClassName("move");
    for(var x = 0; x < data.moves.length; x++){
        moves[x].innerHTML = moveArr[x].name;
        document.images[x].src = "icons\/" + moveArr[x].type + ".jpg";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM