问题
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