首页 > 解决方案 > jQuery slideToggle 动态添加 div

问题描述

我有一些使用slideToggle 的代码。

目前我正在为每一位内容编写jquery,即内容一、内容二、内容三以使用该slideToggle。

我的问题是我想开始添加动态内容,所以我想将硬编码的 content-xx 链接更改为内容并展开,但我不知道该怎么做。

我的代码如下;

<div><a class="expand-one" href="#">[ - ]</a></div>
<div class="clearboth"></div>
<div class="content-one">
    // Content in here
</div>

<div><a class="expand-two" href="#">[ - ]</a></div>
<div class="clearboth"></div>
<div class="content-two">
    // Content in here
</div>

<div><a class="expand-three" href="#">[ - ]</a></div>
<div class="clearboth"></div>
<div class="content-three">
    // Content in here
</div>

<script>
    $(document).ready(function(){
        $('.expand-one').click(function(){
            $('.content-one').slideToggle('slow');
            return false;
        });
        $('.expand-two').click(function(){
            $('.content-two').slideToggle('slow');
            return false;
        });
        $('.expand-three').click(function(){
            $('.content-three').slideToggle('slow');
            return false;
        });
    });
</script>

正如您在此处看到的,我正在为每一位内容编写小 jquery 块,但这在添加动态内容时不起作用。

有什么方法可以将 expand-xxx 更改为仅扩展,将 content-xxx 更改为仅内容,以便我可以添加尽可能多的内容块,并且仍然为每个单独的内容保留 slideToggle?

标签: javascriptjqueryhtml

解决方案


你可以这样做:

 $(document).ready(function() {
   $('.expand').click(function() {
     $(this).parent().nextAll('.content').first().slideToggle('slow');
     return false;
   });
 });

在线演示 (jsFiddle)


推荐阅读