[英]JavaScript and querySelector
I have this HTML:我有这个 HTML:
<div id="allSteps">
<h3>Intermediate steps</h3>
<span class="staticStep">→ <img src="" alt="intermediate step" class="image" ></span>
<span class="staticStep">→ <img src="" alt="intermediate step" class="image"></span>
<span class="staticStep">→ <img src="" alt="intermediate step" class="image"></span>
</div>
In javaScript, how do I access the .src for each image?在 javaScript 中,如何访问每个图像的 .src?
I tried the following but it gives me an error:我尝试了以下操作,但它给了我一个错误:
document.querySelector(".staticStep img").src[0] = images[num][0];
document.querySelector(".staticStep img").src[1] = images[num][1];
document.querySelector(".staticStep img").src[2] = images[num][2];
I also tried the following but it gives me a an error:我也尝试了以下但它给了我一个错误:
document.querySelector(".staticStep img")[0].src = images[num][0];
document.querySelector(".staticStep img")[1].src = images[num][1];
document.querySelector(".staticStep img")[2].src = images[num][2];
What am I doing wrong?我究竟做错了什么?
Try using document.querySelectorAll
which returns all of the possible results instead of just the first one.尝试使用document.querySelectorAll
返回所有可能的结果,而不仅仅是第一个。 The error you're getting ( Uncaught TypeError: Cannot set property 'src' of undefined
) is because querySelector
only returns the first element found, not an array (and elements can't be accessed like arrays).你得到的错误( Uncaught TypeError: Cannot set property 'src' of undefined
)是因为querySelector
只返回找到的第一个元素,而不是数组(并且元素不能像数组一样访问)。
jQuery (the inspiration for querySelector
and querySelectorAll
) always allows you to access like an array ( $('.staticStep img')[0]
works), so this is probably where your confusion stems from. jQuery( querySelector
和querySelectorAll
的灵感)总是允许你像数组一样访问( $('.staticStep img')[0]
工作),所以这可能是你的困惑的根源。
Quick JSFiddle example: http://jsfiddle.net/j8ZUJ/1/快速 JSFiddle 示例: http : //jsfiddle.net/j8ZUJ/1/
document.querySelector returns the first element within the document thus the error. document.querySelector 返回文档中的第一个元素,因此错误。 you probalbly want to try: document.querySelectorAll你可能想尝试: document.querySelectorAll
var elements = document.querySelectorAll(".staticStep img");
elements[0].src =.....
elements[1].src =.....
elements[2].src =.....
Or you could use jQuery instead.或者您可以改用 jQuery。
Try this code试试这个代码
document.querySelector('.staticStep :nth-child(i)').src = images[num][i];
where i = 0,1,2,--- ,n.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.