slideToggle won't work on AJAX rendered content

人走茶凉 提交于 2019-12-25 04:27:23

问题


I've got a simple slideToggle function:

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

and the HTML is like:

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

but the problem is that sometimes this HTML is rendered by ajax and I guess since it didn't get rendered on the page load, the jQuery doesn't see it.

I tried using ajaxComplete:

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

But still nothing....


回答1:


You should definitely use delegated event listeners and never worry about what happens after an AJAX call. Your approach, when fixed, would be piling up listeners after every AJAX call since you're not targetting only the new elements but all of the previous ones as well. Here's how to use a delegated listener:

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

Try it live:

$('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>


来源:https://stackoverflow.com/questions/38597753/slidetoggle-wont-work-on-ajax-rendered-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!