如何遍历 AJAX 加载的复选框

How to loop through AJAX loaded checkboxes?

本文关键字:AJAX 加载 复选框 遍历 何遍历      更新时间:2023-09-26

我想在通过 AJAX 加载的复选框上做这样的事情:

$('input:checkbox').each(function() {
        $(this).hide();
        alert("hi");
        $('<div class="checkbox-fx"><div class="checkbox"></div></div>').insertAfter(this);
    });

在文档加载时,复选框尚未加载,因此不会实现该功能。如何循环浏览新加载的复选框?

谢谢!

假设复选框是使用 $.ajax 之类的东西加载的,您的 success 方法将是您在将生成的 HTML 添加到文档后处理它的位置。

$.ajax({
 // your ajax options here
 success: function(html) {
    $(html).find('input:checkbox').each(function() {
        $(this).hide();
        alert("hi");
        $('<div class="checkbox-fx"><div class="checkbox"></div></div>').insertAfter(this);
    }).appendTo(document.body); // takes the HTML from the ajax call and processes each checkbox. when done, the results are then appended to the document
 }
});
    $.ajax({
    url: '/YourUrl', type: 'Get', dataType: 'json',
    // data: { id:'' },
     success: function(html) {
        $(html).find('input:checkbox').each(function() {
    if($(this).next('div.checkbox-fx').length===0)
    {
            $(this).hide();      
            $('<div class="checkbox-fx"><div class="checkbox"></div></div>').insertAfter(this);
}
        }).appendTo(document.body);
     }
    });