开发者

slideToggle not working on dynamically generated divs

I want to add a lot of

with hidden divs that slideToggle. I don't want to write such a long code that's why I'm trying this:

<html>
<head>

<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript" >


</script>
<script type="text/javascript"> 
$(document).ready(function() {
    //this function does not work when I append the p and div
    $(".flip").click(function() {
        $(this).next().slideToggle("slow");

    });
    var p = $('<p></p>').addClass('flip').text('click here');
    var div = $('<div></div>').addClass('panel').text('hellow world');
    p.append(div);
    $(p).bind('click', function() {

     // alert($(this).text()); //this alert works when i put it as a p.bind
    开发者_Go百科   $(this).next().slideToggle("slow"); //this does not work!! but the previous alert does work....
     });
    $("div#elements").append(p);


});
</script>


<style type="text/css"> 
div.panel,p.flip
{
    margin:0px;
    padding:5px;
    text-align:center;
    background:#e5eecc;
    border:solid 1px #c3c3c3;
}
div.panel
{
    height:120px;
    display:none;
}
</style>
</head>

<body >

<div id="elements" >


 </div>

</body>
</html>

Interesting thing is that the$(flip) function DOES not work with the generated p and div...I then added the function as a (p).bind, and tried it with an alert and it DOES work, but when I want to slideToggle, it doesn't work, does anybody know why?


Interesting thing is that the$(flip) function DOES not work with

the generated p and div...

That's because your p and div elements are dynamically added and are not part of the DOM yet when the page is loaded. Have you tried using the jQuery live API instead?

$(".flip").live("click", function() {
    $(this).next().slideToggle("slow");

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜