如何在插入jQuery代码的div上运行我的jQuery代码?

4

我需要你在代码中的帮助。当我使用jQuery插入新的div时,插入的div不适用于我的jQuery代码。如果有人有解决方案,请告诉我。这是我的HTML代码:

<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>

并且这段jQuery代码

  $(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;


    })



})

感谢您的提前帮助。
4个回答

6

您可以尝试使用.on方法,例如:

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

});

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

没有问题,它在我这里运行良好 :) ,请检查您的jQuery版本。 - Mona Abdelmajeed

3
我创建了一个fiddle,链接为http://jsfiddle.net/mXBkV/1/
$(document).on('mouseenter', 'div.profileInfoSectionwall', function(){
    $(this).children(".remove").show();
});

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

1
实际上,在您的情况下,您需要使用live()方法,因为您想处理当前存在或未来由JQuery创建的DOM元素上的事件。

所以这里是一个适用于您的工作代码:

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

如果您希望对其进行改进,请告诉我


实际上,arunes的回答是最好的。尽管我在我的回答中提出了.live()方法,但我认为最好使用.on()方法来实现最佳实践和代码稳定性,以防将来升级jQuery库。因此,arunes绝对值得获得最佳答案。 - Sidou

0

尝试使用.live函数 在jQuery中实现实时更新

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

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

3
自jQuery 1.7版本起,.live()方法已被弃用。使用.on()来绑定事件处理程序。旧版本的jQuery用户应该优先使用.delegate()而不是.live()。http://api.jquery.com/live/ - arunes
1
@Mona Abdelmajeed,谢谢您的解决方案,它对我很有效,非常感谢。 - Shady Mohamed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接