我目前正在尝试对一些我没有编写或完全理解的代码进行一些工作。页面通过 AJAX 动态调用内容。我正在尝试操纵该内容,但当然,因为当我将其应用于动态内容时页面已经加载,所以它会被忽略。以下是我尝试调用的 jQuery 的一些基本示例:
$(".check").each(function() {
$(this).hide();
var $image = $("<img src='img/checked.png' />").insertAfter(this);
$image.click(function() {
var $checkbox = $(this).prev(".check");
$checkbox.prop('checked', !$checkbox.prop('checked'));
if ($checkbox.prop("checked")) {
$image.attr("src", "img/checked.png");
} else {
$image.attr("src", "img/unchecked.png");
}
})
});
if ($(window).width() < 500) {
$('.panel-collapse').removeClass('in');
} else {
$('.panel-collapse').addClass('in');
}
我怎样才能让它与ajax一起工作?
最佳答案
按照这样的方式使用它。
$image.on('click',function() {
// your script
})
当您动态添加内容时,它需要事件 delegation .
更新:
$("some_parent_id_or_class").on('click','img_with_some_class_or_id',function(){
//your script
})
例如
$("some_parent_id_or_class").on('click','img',function(){
//your script
})
关于javascript - jQuery 无法在 Ajax 上加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896091/