我正在显示阵列中的图像。我希望用户能够从数组中选择一个图像,并用它来替换表中的当前图像img.src。我已设法在单击单元格时向用户显示图像选项,但不确定从何处开始。我在阵列图像上尝试了一个clickhandler,但警报只显示在单击数组中的最后一个图像时。困惑。所有帮助表示赞赏。
function addImage (col) {
var img = new Image(); // Note that a new img variable will be declared each time this function is called
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function () {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src=myImages[i];
var newList = document.createElement("ul");
var newContent = allImages;
newList.appendChild(newContent);
my_div = document.getElementById("showPics");
document.body.insertBefore(newList, my_div);
};
allImages.onclick = function(){
alert("the click is working");//it is but only for the last image...grrrrr
};
//this.src = ????;
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
};
};
document.getElementById('holdTable').appendChild(table);
};
答案 0 :(得分:2)
对于初学者,您需要在循环中移动您的点击作业:
function addImage(col) {
var img = new Image(); // Note that a new img variable will be declared each time this function is called
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function() {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var newList = document.createElement("ul");
var newContent = allImages;
newList.appendChild(newContent);
my_div = document.getElementById("showPics");
document.body.insertBefore(newList, my_div);
allImages.onclick = function(e) {
img.src = e.target.src;
};
};
//this.src = ????;
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
};
};
document.getElementById('holdTable').appendChild(table);
};
...但是,每次单击图像时,您拥有的代码都会重新分配您的点击处理程序,以及重新创建DOM(HTML)元素。您可能需要考虑让它仅在后续点击中隐藏/显示my_div
。