ASP.NET MVC Javascript在页面加载时未首次启动

ASP.NET MVC Javascript not firing the first time on page load

本文关键字:启动 加载 MVC NET Javascript ASP      更新时间:2023-09-26

这应该很简单,但我无法让它发挥作用——当用户单击复选框时,我试图禁用2个下拉列表。

@Html.DropDownList("StartTime", new List<SelectListItem>
{
    new SelectListItem{ Text="10:00 AM", Value = "10:00 AM" },
    new SelectListItem{ Text="12:00 PM", Value = "12:00 PM" },
    new SelectListItem{ Text="2:00 PM", Value = "2:00 PM" }
}
@Html.DropDownList("EndTime", new List<SelectListItem>
{
    new SelectListItem{ Text="10:00 AM", Value = "10:00 AM" },
    new SelectListItem{ Text="12:00 PM", Value = "12:00 PM" },
    new SelectListItem{ Text="2:00 PM", Value = "2:00 PM" }
}
@Html.CheckBox("chkAllDayEvent", new { @onclick = "AllDayEvent_Checked();" })
<script type='text/javascript'>
function AllDayEvent_Checked() {
    $("#chkAllDayEvent").click(function () {
        $('#EndTime').attr("disabled", $(this).is(':checked'));
        $('#StartTime').attr("disabled", $(this).is(':checked'));
    });
}
</script>

我的问题是,当我进入页面时,Javascript直到我点击复选框三次才启动——第三次它会禁用文本框,然后正常工作。

试试这个

$(function(){
    $("#chkAllDayEvent").click(function () {
        $('#EndTime').attr("disabled", $(this).is(':checked'));
        $('#StartTime').attr("disabled", $(this).is(':checked'));
    });
});
@Html.CheckBox("chkAllDayEvent", new { @id = "chkAllDayEvent" })

您不需要AllDayEvent_Checked函数。因为您正在使用jquery绑定它。

function AllDayEvent_Checked() {
        $('#EndTime').attr("disabled", $(this).is(':checked'));
        $('#StartTime').attr("disabled", $(this).is(':checked'));
}
@Html.CheckBox("chkAllDayEvent", new { "@onclick" = "AllDayEvent_Checked();" })

这是因为您有一个函数可以为复选框分配单击处理程序。然后单击复选框时会触发此功能。因此,当第一次单击复选框时,您会为该复选框分配一个单击处理程序,而不是触发单击处理程序,这正是您想要的。

试试这个:

<script type='text/javascript'>
$(document).ready(function () {
    $("#chkAllDayEvent").click(function () {
        $('#EndTime').attr("disabled", $(this).is(':checked'));
        $('#StartTime').attr("disabled", $(this).is(':checked'));
    });
});
</script>
@Html.CheckBox("chkAllDayEvent", new { @id = "chkAllDayEvent" })

试试这个

@Html.CheckBox("chkAllDayEvent", new {@onclick = "AllDayEvent_Checked();" })
function AllDayEvent_Checked() {    
    $('#EndTime').attr("disabled", $("#chkAllDayEvent").is(':checked'));
    $('#StartTime').attr("disabled", $("#chkAllDayEvent").is(':checked'));
}
function AllDayEvent_Checked() {
    $('#EndTime').attr("disabled", $(this).is(':checked'));
    $('#StartTime').attr("disabled", $(this).is(':checked'));
}
@Html.CheckBox("chkAllDayEvent", new { "@onclick" = "AllDayEvent_Checked();" })