我正在尝试通过javaScript DOM在<img>
内添加图像,只是想知道为什么第一个代码有效,而第二个代码无效?为什么img
需要索引?
var img = document.querySelectorAll("img");
img[0].setAttribute("src", "images/image_1.jpg");
img[0].setAttribute("style", "width:500px; height:200px;");
var img = document.querySelectorAll("img");
img.setAttribute("src", "images/image_1.jpg");
img.setAttribute("style", "width:500px; height:200px;");
因为document.querySelectorAll
返回元素列表。
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll