开发者

Add link to image dynamically

开发者 https://www.devze.com 2022-12-22 01:19 出处:网络
If i have \"img\" element id = \"myimg\". Is posible to add link to \"img\" wi开发者_StackOverflow中文版thout edit html page using jQuery

If i have "img" element id = "myimg".

Is posible to add link to "img" wi开发者_StackOverflow中文版thout edit html page using jQuery

<img id="myimg" src="image.png">

I like to make "myimg" have link like this.

<a href="test.html"><img id="myimg" src="image.png"></a>


You can use wrap():

$("#myimg").wrap("<a href='test.html'></a>');

or

$("#myimg").wrap($("<a>").attr("href", "test.html"));

or:

var a = $("<a>").attr("href", "test.html");
$("#myimg").wrap(a);


I am not into jQuery. Using Javascript, you can do something like:

var parentEl = document.getElementById("myimg").parentElement;
var imgEl = parentEl.innerHtml;
parentEl.innerHtml = '<a href="test.html">' + imgEl + '</a>';


$(document).ready(function() {
        var src = "linkhere.html";
        var a = $("<a/>").attr("href", src);
        $("#myimg").wrap(a);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号