dro62273 2011-06-30 03:11
浏览 20
已采纳

将.slideToggle与动态生成的div一起使用

I have divs created within a while loop displaying a MySQL query. I'd like to hide and show them with .slideToggle. I can't use one class as that would trigger every specific div on the page to slide down.

I thought this would repeat within the while loop and find the closest toggleSectionDyn div id. Obviously not.

<div class="actions"><a href="#" id="toggleButtonDyn">Add</a></div>
<div id="toggleSectionDyn">Some content</div>
<script>
  $("#toggleButtonDyn").click(function(){
    $(this).closest("#toggleSectionDyn").slideToggle("slow");
    return false;
  });
</script>
  • 写回答

2条回答 默认 最新

  • douzui0143 2011-06-30 03:13
    关注

    EDIT: live is deprecated. consider using .on()

    you want to use .live()

     $("#toggleButtonDyn").live('click', (function(){
        $(this).closest("#toggleSectionDyn").slideToggle("slow");
        return false;
      });
    

    from the .live() api

    The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

    Now, upon re-reading, I wonder exactly what your asking. You must also make sure each <div> must have a unique ID. You may consider you .next('div') instead of .closest()

    Per the discussion in comments, I would use .next('div') look at the modified jsfiddle from yesterdays question http://jsfiddle.net/ycpgD/

    also, I would strongly recommend using unique ID's. if they cannot be unique make them classes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用