开发者

Using slideToggle() with dynamically added elements

I am having problems with getting my dynamically added elements to toggle using the jquery slidetoggle function. Also, I am using jquery 1.2.6 due to legacy system requirements.

Also, the element toggles, but it seems the toggle occurs the number of times the number of elements there are on the page.

Here is what I have:

.toggleMe {
display:none;}
.toggle {
cursor:pointer;}

$(document).ready(function() { 
    $(".toggle").click(function() { 
        $(this).parents(".reportcontainer").children('.toggleMe').slideToggle('fast');
        return false;
    });
});

<div class="reportcontainer">
    <div class="rbanner toggle">
       <div class="rtitle"><a href="#" class="toggle">CLICK HERE TO TOGGLE</a></div>
       <div class="rexpand toggle expand"></div>
    </div>
    <div class="toggleMe"> HIDDEN / TOGGLED CONTENT </div>
</div>

I'd appreciate any help anyone can give.

Thank you! Dave

EDIT***I figured out my problem - Essentially whenever a user would add the eleme开发者_运维百科nt to the page it would also add the jquery function as well so the function was executing however many times it was on the page.

Thanks for all your suggestions.


your code seems work fine.

But if you copy pasted it "as is" here then you have missing style and script tags

<style>
.toggleMe {
display:none;}
.toggle {
cursor:pointer;}
</style>

<script>
$(document).ready(function() { 
    $(".toggle").click(function() { 
        $(this).parents(".reportcontainer").children('.toggleMe').slideToggle('fast');
        return false;
    });
});
</script>

Best Regards, Max


ideally you would use .live for this, but I'm not sure jquery 1.2 had it. Another thing you could do is run the bind operation again after you add the new elements. When you do it at document.ready, only elements already in the DOM will be bound to the event, so do the same thing after you add the items. (You might need to check that there is no double-binding or something). If there's a problem, you could add an extra class to the new items (say 'pendingbind') and then do a

$(".pendingbind").click(...)<br>
$(".pendingbind").removeClass("pendingbind")

something like that

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜