Warm tip: This article is reproduced from serverfault.com, please click

image-SRC属性不接受JavaScript中的变量

(image - SRC attribute does not accept variables in javascript)

发布于 2020-11-29 11:17:13

有什么办法可以使acceptsrc属性document.createElement成为变量?

我想创建一个模式,当单击图像并且单击的图像以全屏显示时会弹出。但是srcattr不接受变量。

let fScreenImgViewVar = document.getElementsByClassName('fullScreenViewLink');
for (let i = 0; i < fScreenImgViewVar.length; i++) {
    fScreenImgViewVar[i].addEventListener('click', (e) => {
        let imgElem = document.createElement('IMG');
        // here the src attr does not take the variable
        imgElem.src = e.target.id;
        console.log(imgElem)
        document.getElementById('fScreenImgView-img').appendChild(imgElem);
    });
}
Questioner
Apoorva Kumar Shukla
Viewed
0
rags2riches 2020-11-29 19:51:59

你可以尝试解决此问题的setAttribute()方法之一是在新创建的图像上使用该方法,如下所示:

let fScreenImgViewVar = document.getElementsByClassName('fullScreenViewLink');
for (let i = 0; i < fScreenImgViewVar.length; i++) {
  fScreenImgViewVar[i].addEventListener('click', (e) => {
    let imgElem = document.createElement('img');
    imgElem.setAttribute("src", `${e.target.id}`);
    // console.log(imgElem)
    document.getElementById('fScreenImgView-img').appendChild(imgElem);
  });
}

如果此答案可以帮助你解决问题,请考虑接受答案