jQuery 如何使用jquery向图像添加链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8417615/
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-27 10:31:10  来源:igfitidea点击:

how to add a link to an image using jquery?

jquery

提问by Beginner

 <li id ="pdf1"> <img id ="pfd1img" src="/Content/img/pdf.png"/>Catalogue</li>

script:

脚本:

 $("#pdf1img").attr('href', '/Content/pdf/' + data.pdf1);

Im trying to add a hyperlink to an image. I think im nearly there, but im missing something?

我正在尝试向图像添加超链接。我想我快到了,但我错过了什么?

回答by Naftali aka Neal

$("#pdf1img").wrap($('<a>',{
   href: '/Content/pdf/' + data.pdf1
}));

Try that ^^^

试试吧^^^

Image elements cannotbe links, but they can be wrapped in anchor elements which are.

图像元素不能是链接,但它们可以被包裹在锚元素中。

.wrap()in jQuery Docs

.wrap()在 jQuery 文档中

回答by James Allardice

imgelements do not have hrefattributes. If you want the image to act as a link you have a couple of options. You could wrapthe imgin an aelement:

img元素没有href属性。如果您希望图像充当链接,您有几个选择。你可以wrapimg在一个a元素:

$("#pdf1img").wrap("<a href='/Content/pdf/" + data.pdf1 + "'>");

Or you could bind a click event handler to the image and use window.location:

或者您可以将单击事件处理程序绑定到图像并使用window.location

$("#pdf1img").click(function() {
    window.location.href = "/Content/pdf/" + data.pdf1;
});