jQuery hover not working with dynamic elements

后端 未结 2 383
情话喂你
情话喂你 2021-01-17 04:26

Im getting data out of a database, and based on the number of matches, I want to output this:

 
      
2条回答
  •  被撕碎了的回忆
    2021-01-17 05:10

    If you're going to have dynamic data created, don't use an ID to grab them because it is not valid HTML to have two elements with the same ID. Use a class with the same name and it will work fine.

    
    

    Also, as Anoop Joshi points out you cannot use a direct $('#link_delete').hover(...); you need to use a delegate and using what I said from above add the delegate based on the class not the ID, and you should use mouseenter and mouseleave as that is essentially what .hover(func(), func()) is doing.

    $('.link_delete').on({
        mouseenter: function () {
            $(this).attr('src', 'images/account_related/icons/link_delete_h.png');
        },
        mouseleave: function () {
            $(this).attr('src', 'images/account_related/icons/link_delete.png');
        }    
    });
    

    EDIT:

    Added a working jsFiddle that has dynamically created images that will on hover change the image and then back when you're done hovering.

提交回复
热议问题