簡體   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