在页面加载时将Javascript添加到ASP Dropdownlist

Adding Javascript to ASP Dropdownlist on page load

本文关键字:添加 ASP Dropdownlist Javascript 加载      更新时间:2023-09-26

我正在开发一个不使用UpdatePanel的交互式web表单,所以我尝试使用JavaScript来完成大部分功能。对于这个问题,我试图弄清楚如何使用java脚本将函数添加到PageLoad()上的下拉列表中。

我有以下ASP文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Default.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            Discovery Form Templates
            <asp:DropDownList ID="uiFormTemplates" runat="server" DataTextField="Subject" DataValueField="DiscoveryFormID" AppendDataBoundItems="true" OnChange="GetTemplateValue();">
                <asp:ListItem Text="--Select One--" Value=""/>
            </asp:DropDownList>
        </div>
        <div id="ChangePlate"></div>
    </form>
</body>
</html>

然后这个javascript:

function GetTemplateValue()
{
var dropdown = document.getElementById("uiFormTemplates");
var SelectedOption = dropdown.options[dropdown.selectedIndex].value;
if (SelectedOption == null) {
    document.getElementById("ChangePlate").innerText = "There is nothing here.";
}
else {
    document.getElementById("ChangePlate").innerText = dropdown;
}
}

我正在尝试使用以下javascript:

$(document).ready(function () {
    $("#uiFormTemplates").onchange(function () { GetTemplateValue(); });
});

当我从dropdownlist中删除OnChange="GetTemplateValue()"时,即使使用第二个javascript方法,也不会发生任何事情。是我把代码写错了,还是我甚至没有从正确的角度来处理这个问题?无论是对代码的批评还是一些指导现在都会有所帮助,我是一个js noob。

假设您包含jQuery(您正在使用),则没有onchange方法。您必须将其更改为on('change', ...),或者使用change方法。此外,#uiFormTemplates不应该工作,您必须使用控件的ClientID

因此:

$(document).ready(function () {
    $("#<%= uiFormTemplates.ClientID %>").on('change', function () { GetTemplateValue(); });
});

或者:

$(document).ready(function () {
    $("#<%= uiFormTemplates.ClientID %>").change(function () { GetTemplateValue(); });
});