javascript 如何使用jquery创建带有图像作为锚点的链接元素?

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

How to create link element with image as anchor with jquery?

javascriptjqueryhtmlimage

提问by user979390

I know how to create elements with jquery using something like:

我知道如何使用 jquery 创建元素,例如:

$('<div/>').appendTo('body');

How can I create this:

我怎样才能创建这个:

<a href=""><img src="" /></a>

Using the same technique?

使用相同的技术?

回答by dip1232001

$('<img />').attr({
  src:'some image url',
  width:'width in intiger',
  height:'integer'
}).appendTo($('<a />').attr({
  href:'somelink'
}).appendTo($('#someElement')));

回答by anthares

You can first select the html element using jquery and then use the "html()" method to set the desired html. Here is a sample:

您可以先使用 jquery 选择 html 元素,然后使用“html()”方法设置所需的 html。这是一个示例:

$('div.demo-container')
  .html('<a href=""><img src="" /></a>');

The only thing is that you should be able to uniquely identify the desired div that you want to alter. Probably by setting id or class.

唯一的问题是您应该能够唯一地标识您想要更改的所需 div。可能通过设置 id 或 class。

回答by techfoobar

Well.. you can do: $('<a href="http://mysite.com"><img src="/img/img.jpg" /></a>').appendTo('#myDIV')

嗯..你可以这样做: $('<a href="http://mysite.com"><img src="/img/img.jpg" /></a>').appendTo('#myDIV')

回答by Jonathan Christensen

First you need to figure out if there is a wrapping element around where you would like to inject this content. In jquery you would use the function:

首先,您需要确定在要注入此内容的位置周围是否有环绕元素。在 jquery 中,您将使用该函数:

$('.inner').append('<p>Test</p>');

Lets say this was your dom element:

假设这是您的 dom 元素:

<h2>Greetings</h2>
  <div class="container">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
</div>

Any items with the class ".inner" will now be appended a paragraph with the word "test"

任何具有“.inner”类的项目现在都将附加一个带有“test”一词的段落

<h2>Greetings</h2>
  <div class="container">
    <div class="inner">
      Hello
      <p>Test</p>
    </div>
    <div class="inner">
      Goodbye
      <p>Test</p>
    </div>
 </div>

Check out jquery's documentation to find out more: http://api.jquery.com/append/

查看 jquery 的文档以了解更多信息:http: //api.jquery.com/append/

回答by GollyJer

This works by appending an image object.

这通过附加图像对象来工作。

$('<a>', {href:''}).append($('<img>', {src:''}).appendTo('body')