在ajax调用后未设置样式的复选框

本文关键字:样式 复选框 设置 ajax 调用 | 更新日期: 2023-09-27 18:20:06

我有一个脚本文件scripts.js,其中包含一个为页面中的所有复选框设置样式的函数。此文件在母版页中被引用。

有一个用户控件和一个aspx测试页面。在页面加载时,UC会显示一个复选框列表,并应用样式。

单击按钮后,ajax调用从数据库中获取一个列表,并将更多复选框绑定到页面。但对于新的复选框,不应用样式。可能出了什么问题。

scripts.js:

function selectcheckBtn() {   
    alert(1); 
    if ($("input:checkbox").prev("span").length === 0) {
        alert(2); 
        $("<span class='uncheked'></span>").insertBefore("input:checkbox")
    }
    $("input:checkbox").click(function () {
        check = $(this).is(":checked");
        if (check) {
            $(this).prev("span").addClass("cheked").removeClass("uncheked")
        } else {
            $(this).prev("span").addClass("uncheked").removeClass("cheked")
        }
    });
    $("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
}

ctrl.ascx:

<script>
function ShowMore() {
        $.ajax({
            url: "/_layouts/15/handlers/ShowMore.ashx",            
            data: {},
            success: function (msg) {    
//append new chkbox list to existing list. It is hidden at first and later faded in.               
                $(".divList").append(msg); 
                    selectcheckBtn();
                    $(".hideDiv").fadeIn(300).removeClass("hideDiv");                    
                },
            error: function (msg) {
                alert("An error occurred while processing your request");                
            }
        });
    }
</script>
<a href="javascript:;" id="btnMore" runat="server" onclick="ShowMore();">Show more </a>

在页面加载时,两个警报都会弹出。但单击"显示更多"时,只会弹出警报(1)。

浏览器控制台中没有错误。

渲染HTML:

//with style applied to chkboxes on page load
<div><span class="uncheked"></span><input type="checkbox" runat="server"  id="406">
<label>Compare</label></div>
//with no style applied to new chkboxes
<div><input type="checkbox" runat="server" id="618"><label>Compare</label></div>

在ajax调用后未设置样式的复选框

我不明白为什么selectcheckBtn();中的if条件对于新的chkboxes不成立。因此,为复选框添加了一个新类,并编写了此解决方法。现在调用这个函数而不是ajax代码中的selectcheckBtn();,就成功了。

function StyleCheckBox() {
        $(".chkBx").each(function () {
            if ($(this).prev("span").length === 0) {
                $("<span class='uncheked'></span>").insertBefore($(this));
            }            
            $("input:checkbox").click(function () {
                check = $(this).is(":checked");
                if (check) {
                    $(this).prev("span").addClass("cheked").removeClass("uncheked")
                } else {
                    $(this).prev("span").addClass("uncheked").removeClass("cheked")
                }
            });
            $("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
        });        
    }