将图像加载到DIV标记中

时间:2010-03-10 09:54:18

标签: jquery

我在div标签中有一个标识为sIMG的图片列表。

示例:

<div id="sIMG">
<img src="1.jpg" title=""/>
<img src="2.jpg" title=""/>
<img src="3.jpg" title=""/>
<img src="4.jpg" title=""/>
<img src="5.jpg" title=""/>
<img src="6.jpg" title=""/>
</div>

现在,如果我点击任何图片,我需要将其加载到sIMG div标签。

我的代码如下所示,但似乎只在第一张图片中加载:

jQuery(document).ready(function(){
    jQuery('#sIMG img').click(function(){

        /* Get the sources */
        var currentSRC = jQuery('#sIMG img').attr('src');
        var altSRC = jQuery('#sIMG img').attr('title');
        alert(currentSRC)
        /*Fade, Callback, swap the alt and src, fade in */
        jQuery('#IMGHolder').fadeOut('fast',function(){
            jQuery('#IMGHolder').html('<img src='+currentSRC+' title='+altSRC+' />');
            jQuery('#IMGHolder').fadeIn('fast');
        });
    });
});

我在这里做错了吗?

2 个答案:

答案 0 :(得分:2)

使用

$(this)访问事件处理程序中的当前元素。

jQuery(document).ready(function(){
        jQuery('#sIMG img').click(function(){
            /* Get the sources */
            var currentSRC = jQuery(this).attr('src');

            var altSRC = jQuery(this).attr('title');

            alert(currentSRC);

            /*Fade, Callback, swap the alt and src, fade in */

            jQuery('#IMGHolder').fadeOut('fast',function(){
                jQuery(this).html('<img src='+currentSRC+' title='+altSRC+' />').fadeIn("fast");                    
            });
        });

    });

答案 1 :(得分:1)

  

我在这里做错了吗?

可能。处理程序$(this)内部将为您提供有关所单击对象的jQuery句柄。你可能想要jQuery(this)

无论点击事件如何,您当前的代码都会显示出来并查找img个元素。

您的HTML格式错误:

<div id="sIMG">
<img src="1.jpg" title=""/>
<img src="2.jpg" title="""/>
<img src="3.jpg" title="""/>
<img src="4.jpg" title="""/>
<img src="5.jpg" title="""/>
<img src="6.jpg" title=""/>
</div>

应该是

<div id="sIMG">
    <img src="1.jpg" title=""/>
    <img src="2.jpg" title=""/>
    <img src="3.jpg" title=""/>
    <img src="4.jpg" title=""/>
    <img src="5.jpg" title=""/>
    <img src="6.jpg" title=""/>
</div>

忽略缩进,这是"""我遇到的问题。