1

我正在显示数组中的图像。我希望用户能够从数组中选择一个图像,并让它替换表中的当前图像 img.src。当单击单元格时,我设法向用户显示图像选择,但不确定从这里去哪里。我在数组图像上尝试了一个点击处理程序,但警报仅在单击数组中的最后一个图像时显示。使困惑。所有帮助表示赞赏。

  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);
    };
4

1 回答 1

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在后续点击时隐藏/显示。

于 2013-01-02T14:05:42.423 回答