简体   繁体   中英

How to run my jquery code on div that inserted form jquery code?

I need your help in my code I have problem when new div inserted from jquery the inserted div does not apply to my jquery code if anyone have solution please tell me and this my Html code

<input type="text" id="t" value=""/>
<a href="#" class="btn">click</a><br/>
<br/>
<div  class="profileInfoSectionwall"style="border:1px solid #ccc">
text111111

    <div class="remove" style="display: none;">
        <a class="post_remove" rel="1" herf="#">X</a>
    </div>
</div>
<br/>
<div  class="profileInfoSectionwall"style="border:1px solid #ccc">
text222222

    <div class="remove" style="display: none;">
        <a class="post_remove" rel="2" herf="#">X</a>
    </div>
</div>

and this jquery code

  $(document).ready(function(){
$(".profileInfoSectionwall").mouseenter(function(){
         $(this).children(".remove").show();

     });
     $(".profileInfoSectionwall").mouseleave(function(){
             $(".remove").hide();

         });

    $(".btn").click(function(){
         var s=$("#t").attr("value");
        $(this).after("<br/><br/><div class='profileInfoSectionwall' style='border:1px solid #ccc'>"+s+"<div class='remove' style='display: none;'><a class='post_remove' rel='3' herf='#'>X</a></div></div>");
    return  false;


    })



})

thanks in advance

You may want to try using the .on method so something like:

$(".profileInfoSectionwall").on('mouseenter', function(){
     $(this).children(".remove").show();

});

$(".profileInfoSectionwall").on('mouseleave', function(){
    $(".remove").hide();
});

I created fiddle http://jsfiddle.net/mXBkV/1/

$(document).on('mouseenter', 'div.profileInfoSectionwall', function(){
    $(this).children(".remove").show();
});

$(document).on('mouseleave', 'div.profileInfoSectionwall', function(){
    $(".remove").hide();
});

Actually what you need in your case is the live() method as you want to handle events on currently existing OR future DOM elements (ie: created by JQuery).

So here is a working code for you :

http://jsfiddle.net/sidou/CMab3/

let me know if you want some improvement on it

try .live function live in jquery

 $(".profileInfoSectionwall").live('mouseenter', function(){
    $(this).children(".remove").show();
});

$(".profileInfoSectionwall").live('mouseleave', function(){
    $(this).children(".remove").hide();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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