0

我有一个带有“onclick”功能的链接。当按下它时,它会将一个 img 元素附加到一个名为“mediaBox”的单独 div 中。我遇到的问题是,如果它被多次按下,那么它会附加更多的 img 实例。我该如何控制这个。我还是 JavaScript 的新手,我更喜欢用纯 Javascript 而不是 jQuery 来接收这个答案,因为在我完全理解 Javascript 之后,我会跨过那座桥。

var rkf = document.getElementById("submenulinks").getElementsByTagName("li")[0];

rkf.onclick = function(){
    var client = document.getElementById('client');
    var description2 = document.getElementById('description2');
    var role = document.getElementById('role');
    var mediaBox = document.getElementById('mediaBox'); 
    var thumb = document.getElementById("thumb");       
    var client2 = document.getElementById("client2");
    var newImage = document.createElement("img");

    client2.innerHTML = "Role - Applications";
    client.innerHTML = "RKF Real Estate";
    client2.innerHTML = "Role - Applications";
    description2.innerHTML = "Quarterly Catalog of Exclusive Listings managed by RKF";
    role.innerHTML = "Custom designed Cover and listings content. Tables were also utilized within Indesign. <br><br><b><i> Photoshop and Indesign</i></b>";

    newImage.setAttribute("src", "../images/rkf_cover.jpg");
    newImage.setAttribute("height", "500px");
    newImage.setAttribute("width", "387px");
    newImage.setAttribute("alt", "rkf");
    newImage.setAttribute("href", "#");
    mediaBox.style.backgroundImage = "none";
    document.getElementById("mediaBox").appendChild(newImage);
    newImage.style.display = "block";
    newImage.style.marginLeft = "auto";
    newImage.style.marginRight = "auto";
    newImage.style.marginTop = "25px";  
}           
4

1 回答 1

0
rkf.onclick = function(){
    var client = document.getElementById('client');
    ...
    ...
    ...

    // Remove the handler after it ran once.
    this.onclick = null; // <<<<<========================
}     

由于您将来确实想使用 jQuery,因此它等于:

$('#submenulinks li:first').one('click', handler);
于 2013-04-15T07:05:27.753 回答