我在 Default.aspx 中插入了四个相同的 UserControl。我想将数据写入 HiddenField 并使用 javascript 将此数据写入 Label1。
该方法仅适用于最后加载的 UserControl - HiddenFieldLoader3。
为什么该方法不适用于所有用户控件?我怎样才能修复我的代码?
默认.aspx
<%@ Register Src="~/HiddenFieldLoader.ascx" TagPrefix="uc1" TagName="HiddenFieldLoader" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Default.aspx</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="HiddenFieldLoader.js"></script>
</head>
<body>
<form id="form1" runat="server">
<uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader" />
<uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader1" />
<uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader2" />
<uc1:HiddenFieldLoader runat="server" ID="HiddenFieldLoader3" />
</form>
</body>
</html>
用户控件:HiddenFieldLoader.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HiddenFieldLoader.ascx.cs" Inherits="NewControls.HiddenFieldLoader" %>
<script type="text/javascript">
HFLoader.declareVariables("<%=Button1.ClientID %>", "<%=HiddenField1.ClientID %>", "<%=Label1.ClientID %>");
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" />
<input type="button" ID="Button1" value="Save" runat="server" />
<input type="button" ID="Button2" onclick="HFLoader.showEvent();" value="Show" runat="server" />
Javascript 文件:HiddenFieldLoader.js
HFLoader = {
button: null,
hiddenField: null,
label: null,
declareVariables: function (btn, hf, label) {
HFLoader.button = btn;
HFLoader.hiddenField = hf;
HFLoader.label = label;
},
///////SHOW EVENT
showEvent: function () {
$("#" + HFLoader.label).html($("#" + HFLoader.hiddenField).val());
},
//////!SHOW EVENT
saveHiddenField: function (data) {
$("#" + HFLoader.hiddenField).val(data);
},
buttons: function () {
$("#" + HFLoader.button).click(function () {
var datatest = "Data from button ID: " + $(this).attr("id");
HFLoader.saveHiddenField(datatest);
$("#" + HFLoader.label).html($("#" + HFLoader.hiddenField).val());
return false;
});
},
init: function () {
$(function () {
HFLoader.buttons();
});
}
};
HFLoader.init();