jQuery 如何使用jQuery在div中附加图像?

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

How to append an image in div using jQuery?

jquerycssoop

提问by Mary

I have a list of small images while clicking on each of them they should show up in the div(the idea is to see them bigger)

我有一个小图片列表,点击每个小图片,它们应该显示在 div 中(想法是看到它们更大)

I have used append function jQuery but it does not work

我使用了追加函数 jQuery 但它不起作用

Here is the jQuery code:

这是jQuery代码:

$(function() {
    $('.selectable a img').click(function() {
    var img=$(this).attr('src');    
    alert(img);// this is what i get  data/100.jpg but it does not show up in div
    ('#div1').append('img');
  });

});

part of CSS Code:

CSS 代码的一部分:

 <ul> 
    <?php foreach ($cakeTypeService->getByTypeAndSubtype('stage', 'ROSE') as $cake) { ?>
     <li class="selectable" id="cakeType-<?= $cake->id ?>">
       <a href="?cakeType=<?php echo ($cake->id); ?>" title="Selecteer">
       <?php if ($cake == $order->cakeType){?><span class="checked"></span><?php } ?>
       <img src="data/<? echo $cake->id ?>.jpg" alt="" width="50" height="50" /></a>                                 
      </li>
     <?php } ?>
  </ul>

回答by Bar?? Velio?lu

Have you tried ?

你有没有尝试过 ?

$(function() {
    $('a img').click(function() {
    $img=$(this).attr('src');    

    $('#div1').append("<img src="+$img+" />")

  });

});

回答by chhameed

you can see this live demo right here http://jsfiddle.net/chhameed/nWqcv/

你可以在这里看到这个现场演示 http://jsfiddle.net/chhameed/nWqcv/

Hope it helps .

希望能帮助到你 。

回答by Gavin Osborn

I know your question specifically asked for how to manually achieve this but there are existing plugins out there that would do the bulk of this work for you:

我知道您的问题专门询问了如何手动实现这一点,但现有的插件可以为您完成大部分工作:

A great example here.

这里是一个很好的例子

Another example here.

另一个例子在这里

You could use this plugin or at least use it for inspiration to write your own.

你可以使用这个插件,或者至少用它来获得灵感来编写你自己的插件。

回答by Nicola Peluchetti

you are missing a $ (here ('#div1')) and doing some weird things with what you append (actually you are trying to append a collecttion of all images on the page. (selected with $('img');

您缺少一个 $(此处为 ('#div1')) 并且对您附加的内容做了一些奇怪的事情(实际上您正在尝试附加页面上所有图像的集合。(用 $('img') 选择);

try this:

尝试这个:

$(function() { 
$('.selectable a img').click(function() { 
var img=$(this);//img is the image clicked
//append the img to the div
$('#div1').append(img); });

});

EDIT added comments

编辑添加评论