动态添加图像和悬停事件

时间:2012-08-05 08:59:37

标签: jquery

我试图找到一种方法来动态添加带有一些悬停功能的图像。谢谢。

<ul id="imagesList">
  <li>No images found</li>
</ul>

$(function(){
            //load image array
            var images = {'image1':'assets/img/linkedin_30px.png','image2':'assets/img/twitter_30px.png'};
            $.each(images, function(){
               ....?
            });
        });

2 个答案:

答案 0 :(得分:0)

查看event delgation。这样,您可以将事件处理程序分配到一个位置,并使其可以更改domnodes。在你的情况下,它可能看起来像这样:

$('#imagesList').on('hover', 'img', function(){
    // your hover event handler here
});

然后你可以创建图像节点:

$('#imagesList').html('');
var images = {'image1':'assets/img/linkedin_30px.png','image2':'assets/img/twitter_30px.png'};
$.each(images, function(i, src){
    $('#imagesList').append('<li><img src="'+src+'"></li>');
});

以下是演示:http://jsfiddle.net/pwGQX/

答案 1 :(得分:0)

我需要更多细节,但很快,您可以使用jQuery的.hover事件;

    $("#imagesList").hover(
      // prepend the image on hover
      function() {
          $( this ).prepend( $( "<span><img src='image-x.jpg'></span>" ) );
        },
      // Remove the image when mouse leaves
        function() {
          $( this ).find( "span:first" ).remove();
      }
    );
相关问题