简体   繁体   English

在jQuery中单击图像后如何在另一个div中显示图像

[英]how to show an image in another div after clicking the image in jquery

I have an image in my webpage i want when the user click on the image the current image also appear in the other div i have in my web page i am totally confuse please help me out here is my code. 我的网页中有一个图像,我希望当用户单击该图像时,当前图像也出现在我的网页中的其他div中,我完全感到困惑,请帮我解决这是我的代码。

<div id="img"><img src="download1.jpg"></div>

<div><img src="" class="img2"></div>

<img src="download1.jpg" alt="" class="imgs" id="the_id" width="180" height="60" />
<script type="text/javascript">
$(document).ready(function() {
  $('.imgs').click(function(){
    var idimg = $(this).attr('id');
    var srcimg = $(this).attr('src');
    alert('ID is: '+ idimg+ '\n SRC: '+ srcimg);
    $(".img2").attr('src',srcimg);
  });
});
</script>

Fiddle 小提琴

Tried using a fiddle and it works, here is the code which I used. 使用小提琴进行了尝试,并且可以使用,这是我使用的代码。

HTML 的HTML

<div id="img"><img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTgAVjAiDPV-oy-o9mvdHEsVoACUKJIuFcn08RJ5kRYINY4oqjPcA"></div>

<div><img src="" class="img2"></div>

<div>click me </div>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTgAVjAiDPV-oy-o9mvdHEsVoACUKJIuFcn08RJ5kRYINY4oqjPcA" alt="" class="imgs" id="the_id" width="180" height="60" />

Jquery jQuery的

$(document).ready(function() {
  $('.imgs').click(function(){
    var idimg = $(this).attr('id');
    var srcimg = $(this).attr('src');
    alert('ID is: '+ idimg+ '\n SRC: '+ srcimg);
    $(".img2").attr('src',srcimg);
  });
});

您的代码是完美的,可以正常工作,以检查是否正确加载了jquery库,但您的代码中没有看到任何错误。

You can achieve this by setting the destination image's src to the same as the img src in the clicked div. 您可以通过将目标图像的src设置为与所单击的div中的img src相同来实现此目的。 Try: 尝试:

$('.source-img').on('click', function(){
    var src = $(this).children('img').attr('src');  
    $('#destination').children('img').attr('src', src);
});

Check out this jsFiddle . 看看这个jsFiddle

If you want the images to not have wrappers, then just change the jQuery targetting and leave out the .children(img) part. 如果您希望图像不具有包装器,则只需更改jQuery目标并忽略.children(img)部分。

If you're looking for a better method, see this JSFiddle 如果您正在寻找更好的方法,请参阅此JSFiddle

It uses the clone function 它使用克隆功能

$('.imgs').click(function(){
    $(this).clone().appendTo('#LoadImageHere').attr('id', 'ClonedImage');
});

It means you don't have an image with an empty src attribute lying around, and you can add attributes to the cloned image as you wish (I added an ID in the example). 这意味着您没有一个带有空src属性的图像,并且可以根据需要向克隆的图像添加属性(我在示例中添加了一个ID)。

如果尝试使用此代码或此处的组合进行宽度设置,您将获得非常有趣的结果。“ Plz外观”。Div元素在自身img标签中具有宽度源图像,类“ img2”。图库中的其他图像必须具有相同的ID,例如ID为“ the_id” “并且,如果我们单击任何图片,该图片将显示在div标签的空间中。如何获得弹跳效果图片必须具有相同的大小。我将两个div标签组合在一起,其中冷杉的类为“ img2”,第二个是我的图片分发我的图片,使用此页面上的第一个代码,我会创建一个不错的图片库。尝试一下,这并不难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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