如果点击它,下面的代码会显示图像并选择其中一个(带蓝色边框)。它还将所选的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);
答案 0 :(得分:2)
您使用错误的方式添加元素事件。您的活动未被触发。
改为使用这种方式:
var imagetag = document.createElement("img");
imagetag.onclick = function () {
myfun(i);
};
答案 1 :(得分:1)
试试这个:
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);