简体   繁体   中英

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

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

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

How can I create this:

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

Using the same technique?

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

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

$('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.

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

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:

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

Lets say this was your dom element:

<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"

<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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM