繁体   English   中英

为什么会出现这个?:clone.getElementById 不是 function

[英]why is this appearing ?: clone.getElementById is not a function

我有这个错误:

index.js:29 Uncaught TypeError: clone.getElementById 不是 function
在 HTMLButtonElement.changeImg (index.js:29:11)
changeImg @ index.js:29

它标记突出显示的行。 我不明白为什么。 如果有人可以帮助我,我将不胜感激。

 //captura de elementos: const btn = document.querySelector('.btn'); const templateImg = document.querySelector('.templateImg').content; const imgContainer = document.querySelector('.imgContainer'); const fragment = document.createDocumentFragment(); let arrayImg = [ "/img/food1.jpg", "/img/food2.jpg", "/img/food3.jpg", "/img/food4.jpg", "/img/food5.jpg", "/img/food6.jpg", "/img/food7.jpg", "/img/food8.jpg", "/img/food9.jpg" ]; const changeImg = () => { let ran = Math.floor(Math.random() * 9); //Crear clon del template: const clone = templateImg.firstElementChild.cloneNode(true); console.log(clone); console.log(arrayImg[ran]); //capturar elemento y modificar el src: clone.getElementById("img").src = arrayImg[ran]; fragment.appendChild(clone); imgContainer.appendChild(fragment); } btn.addEventListener('click', changeImg);
 <,DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="StyleSheet" href= "style.css" type= "text/css"> <title>Cambiador de imagenes</title> </head> <body> <div class="container"> h1>Food and drink in Florianopolis</h1> <div class="imgContainer"><.--templateImg--></div> <button type="text" class="btn" id="btn">Change</button> </div> <template class="templateImg"> <img id="img" src="/img/food1.jpg"> </template> <script src="./index.js"></script> </body> </html>

我试图通过修改src来更改模板中的图像:

<template class="templateImg">
    <img id="img" src="/img/food1.jpg">
</template>

当我使用querySelector时,错误是我尝试替换的值是 null,即使它不是,并且使用getElementById时,我得到的消息是它不是 function。

你用这段代码创建一个“克隆”:

const clone = templateImg.firstElementChild.cloneNode(true);

这是一个图像元素(见控制台),你改变图像 src 只需要使用这个代码:

clone.src = arrayImg[ran];

getElementById()是一种不属于任何 HTML 元素的document方法。

您想要使用的是querySelector ,您实际上可以在元素上使用它。

暂无
暂无

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

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