如何在Javascript中为另一个IMG创建div,link和img

时间:2014-03-01 18:54:47

标签: javascript html

我有这张照片:

<img src="cards.png" id="img"> <!--CARD PICTURE-->

这就是我需要的:

<div class="container_img">
    <img src="cards.png" id="img"> <!--CARD PICTURE-->
    <div class="share_container">
        <a href="https://www.facebook.com/sharer/sharer.php?u=http://google.com" target="_blank">
            <img src="http://emmanuelorozco.com/shareFacebook.png" class="shareButtonMedia">
        </a>
        <a href="http://twitter.com/share?u=http://google.com" target="_blank">
            <img src="http://emmanuelorozco.com/shareTwitter.png" class="shareButtonMedia">
        </a>
    </div>
</div>

正如你所看到的,它是相同的图片,但添加了一些div,链接和其他图片。

我试过的是:

var img  = document.getElementById("img");
var par = img.parentNode;
var div  = document.createElement("div");
var shareLinks = document.createElement("a");

par.insertBefore(div,img);
div.appendChild(img);
div.setAttribute("class","container_img");
div.appendChild(img);

它让我回答:

<div class="container_img">
    <img src="cards.png" id="img"> <!--CARD PICTURE-->
</div>

但我无法找到如何执行其余代码。任何人都可以帮我一把吗?

感谢。

1 个答案:

答案 0 :(得分:2)

以下是您需求的完整代码。

DEMO

var img  = document.getElementById("img");
var par = img.parentNode;
var div  = document.createElement("div");
var shareLinks = document.createElement("a");

par.insertBefore(div,img);
div.appendChild(img);
div.setAttribute("class","container_img");
div.appendChild(img);

//UPDATE img4 and img5, 
// as many as image you want, you should create more elements.
// it woudl be good if we define funciton for this. 
var img4  = document.createElement("img");
img4.setAttribute("src", "http://emmanuelorozco.com/shareFacebook.png");
div.appendChild(img4);

var img5  = document.createElement("img");
img5.setAttribute("src", "http://emmanuelorozco.com/shareTwitter.png");
div.appendChild(img5);

var anotherDiv = document.createElement("div");
anotherDiv.className = "share_container";

var anchor = document.createElement("a");
anchor.setAttribute("href", "https://www.facebook.com/sharer/sharer.php?u=http://google.com");
anchor.setAttribute("target", "_blank");

var img2  = document.createElement("img");
img2.setAttribute("src", "http://emmanuelorozco.com/shareFacebook.png");
img2.setAttribute("class", "shareButtonMedia");
anchor.appendChild(img2);

anotherDiv.appendChild(anchor);
div.appendChild(anotherDiv);


var anchor2 = document.createElement("a");
anchor2.setAttribute("href", "http://twitter.com/share?u=http://google.com");
anchor2.setAttribute("target", "_blank");

var img3  = document.createElement("img");
img3.setAttribute("src", "http://emmanuelorozco.com/shareTwitter.png");
img3.setAttribute("class", "shareButtonMedia");
anchor2.appendChild(img3);

anotherDiv.appendChild(anchor2);
div.appendChild(anotherDiv);
document.getElementById('container').appendChild(div);