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
how to add a link to an image using 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.
图像元素不能是链接,但它们可以被包裹在锚元素中。
回答by James Allardice
img
elements do not have href
attributes. If you want the image to act as a link you have a couple of options. You could wrap
the img
in an a
element:
img
元素没有href
属性。如果您希望图像充当链接,您有几个选择。你可以wrap
在img
在一个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;
});