Add link to image dynamically

回眸只為那壹抹淺笑 提交于 2020-06-08 04:24:08

问题


If i have "img" element id = "myimg".
Is posible to add link to "img" without 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>

回答1:


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



回答2:


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>';



回答3:


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


来源:https://stackoverflow.com/questions/2400218/add-link-to-image-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!