slideToggle不适用于AJAX呈现的内容 [英] slideToggle won't work on AJAX rendered content

查看:87
本文介绍了slideToggle不适用于AJAX呈现的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的slideToggle函数:

I've got a simple slideToggle function:

    $('.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看不到它.

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.

我尝试使用ajaxComplete:

I tried using ajaxComplete:

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

但还是没有....

推荐答案

您绝对应该使用委派的事件侦听器不必担心AJAX调用后会发生什么.固定后,您的方法将在每次AJAX调用之后堆积侦听器,因为您不仅要定位新元素,还要定位所有先前元素.使用委托侦听器的方法如下:

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>

这篇关于slideToggle不适用于AJAX呈现的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆