通过链接创建动态img而不附加多个实例

时间:2013-04-15 07:03:02

标签: javascript

我有一个附带“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";  
}           

1 个答案:

答案 0 :(得分: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);