【问题标题】:slideToggle won't work on AJAX rendered contentslideToggle 不适用于 AJAX 呈现的内容
【发布时间】:2016-07-26 18:52:17
【问题描述】:

我有一个简单的 slideToggle 函数:

    $('.toggle-within').click(function () {
        $('.toggle-this', this).slideToggle('fast');
    });

HTML 是这样的:

<div class="toggle-within">
  CLICK FOR DETAILS
  <p class="toggle-this">
    DETAILED TEXT
  </p>
</div>

但问题是有时这个 HTML 是由 ajax 渲染的,我猜因为它没有在页面加载时渲染,所以 jQuery 看不到它。

我尝试使用 ajaxComplete:

$(document).ajaxComplete(function () {
    $('.toggle-within').click(function () {
        $('.toggle-this', this).slideToggle('fast');
    });
});

但还是什么都没有……

【问题讨论】:

    标签: jquery ajax dom slidetoggle


    【解决方案1】:

    您绝对应该使用delegated event listeners,并且永远不要担心 AJAX 调用后会发生什么。您的方法在修复后将在每次 AJAX 调用后堆积侦听器,因为您不仅针对新元素,而且还针对所有以前的元素。以下是如何使用委托侦听器:

    $('body').on('click', '.toggle-within', function () {
        $('.toggle-this', this).slideToggle('fast');
    });
    

    现场试用:

    $('body').on('click', '.toggle-within', function () {
        $('.toggle-this', this).slideToggle('fast');
    });
    
    function add(){
      var content = "<div class=\"toggle-within\">"+
      "CLICK FOR DETAILS"+
      "<p class=\"toggle-this\">"+
        "DETAILED TEXT FROM AJAX"+
      "</p>"+
    "</div>"
      document.body.innerHTML += content;
    }
    .toggle-this {display: none}
    .toggle-within:hover {cursor: pointer; color: #aaa}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button onclick="add()">Simulate AJAX</button>
    <div class="toggle-within">
      CLICK FOR DETAILS
      <p class="toggle-this">
        DETAILED TEXT
      </p>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多