下面的代码显示图像,如果我单击它,则选择其中之一(带有蓝色边框)。它还将所选变量的src存储在变量(src1
)中,但这最后一点不起作用。我的错在哪里感谢你们!
var src1 = "";
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
img[2] = new Image();
img[2].src = "../images/poggiatesta3.jpg";
for (var i = 0; i < img.length; i++) {
var imagetag = document.createElement("img");
var onclick = document.createAttribute("onclick");
onclick.value = "myfun(" + i + ")";
var sorc = document.createAttribute("src");
sorc.value = img[i].src;
var id = document.createAttribute("id");
id.value = "my_image" + i;
var clas = document.createAttribute("class");
clas.value = "my_image_clas";
imagetag.setAttributeNode(clas);
imagetag.setAttributeNode(onclick);
imagetag.setAttributeNode(sorc);
imagetag.setAttributeNode(id);
document.body.appendChild(imagetag);
}
function myfun(i) {
src1 = document.getElementById('my_image' + i).src;
}
var _last = null;
function select(element) {
element.onclick = function () {
element.classList.toggle('selected');
if (_last) _last.classList.remove("selected");
_last = element.classList.contains("selected") ? element : null;
}
}
Array.from(document.getElementsByClassName('my_image_clas')).forEach(select);
最佳答案
尝试这个:
var src1 = "";
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
img[2] = new Image();
img[2].src = "../images/poggiatesta3.jpg";
for (var i = 0; i < img.length; i++) {
var imagetag = document.createElement("img");
var sorc = document.createAttribute("src");
sorc.value = img[i].src;
var id = document.createAttribute("id");
id.value = "my_image" + i;
var clas = document.createAttribute("class");
clas.value = "my_image_clas";
imagetag.setAttributeNode(clas);
imagetag.setAttributeNode(sorc);
imagetag.setAttributeNode(id);
document.body.appendChild(imagetag);
}
var _last = null;
function select(element) {
element.onclick = function () {
element.classList.toggle('selected');
if (_last) _last.classList.remove("selected");
_last = element.classList.contains("selected") ? element : null;
src1 = _last.src;
}
}
Array.from(document.getElementsByClassName('my_image_clas')).forEach(select);
关于javascript - 保存图片的src的功能不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35741945/