Javascript 动态添加图片链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2400218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:07:32  来源:igfitidea点击:

Add link to image dynamically

javascriptjqueryimagehyperlinkhref

提问by wearetherock

If i have "img" element id = "myimg".
Is posible to add link to "img" without edit html page using jQuery

如果我有“img”元素 id =“myimg”。
可以在不使用 jQuery 编辑 html 页面的情况下将链接添加到“img”

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

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

我喜欢让“myimg”有这样的链接。

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

回答by cletus

You can use wrap():

您可以使用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);

回答by Kangkan

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

我不喜欢jQuery。使用 Javascript,您可以执行以下操作:

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

回答by Tr1stan

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