gpt4 book ai didi

javascript - 在 aspx 页面中使用 aspx 用户控件的多个实例

转载 作者:行者123 更新时间:2023-12-03 22:35:27 31 4
gpt4 key购买 nike

我在 aspx 页面中使用多个 aspx 用户控件实例时遇到问题。当我尝试通过 Java 脚本获取用户控件元素值时会发生这种情况。

用户控制代码:

<script type="text/javascript">
function ucFun()
{
var a = document.getElementById("<%=tbName.ClientID%>");
alert(a.value);
return false;
}
</script>
<asp:Label Text="Name" runat="server" ID="lblname"></asp:Label>
<asp:TextBox ID="tbName" runat="server" ></asp:TextBox>
<asp:Button ID="btSubmit" runat="server" Text="Go" OnClientClick="ucFun()" />

网页表单代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc:cont runat="server" ID="ucID" />
<uc:cont runat="server" ID="Cont1" />
<uc:cont runat="server" ID="Cont2" />
</div>
</form>
</body>
</html>

单击 Go 按钮时,它会在警报框中显示 null,因为该元素未定义。
但是,当我在表单中有一个用户控件实例时,它正确地显示了文本框的值。

有什么办法我们应该写这个..

最佳答案

经过一番搜索,找到了不同的解决方案。

http://www.aspsnippets.com/Articles/Issue-JavaScript-in-WebUserControl-not-working-when-used-multiple-times-on-same-page.aspx

在这里,他们附加了一个带有 javascript 名称的 uniqueID,因此与 javascripts 没有冲突。

用户控制.CS

protected string uniqueKey;
protected void Page_Load(object sender, EventArgs e)
{
this.uniqueKey = Guid.NewGuid().ToString("N");
this.Button1.Attributes["onclick"] = "return DisplayMessage_" + uniqueKey + "();";
}

用户控制.aspx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_TestCS.ascx.cs" Inherits="UC_TestCS" %>
<script type ="text/javascript">
function DisplayMessage_<%=uniqueKey %>() {
var message = document.getElementById("<%=TextBox1.ClientID %>").value;
alert(message);
return false;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show Message" />

关于javascript - 在 aspx 页面中使用 aspx 用户控件的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21303655/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com