首页 > 解决方案 > 实时更改中继器内的标签

问题描述

我正在尝试根据也在转发器内的文本框的值实时更改转发器内的标签。

我曾尝试使用 JS 解决此问题,但无法访问标签或中继器内的文本框。

如果标签或文本框在中继器之外,我可以毫无问题地访问它

JS:

<script language="javascript" type="text/javascript">
    document.getElementById('<%=labelToUpdate.ClientID%>').innerHTML = document.getElementById('<%=txtInput.ClientID%>').value;
</script>

ASPX:

<asp:TextBox ID="txtInput" runat="server" class="form-control"></asp:TextBox>
<asp:Label ID="labelToUpdate" runat="server"></asp:Label>

任何帮助总是很感激。

谢谢

标签: javascriptc#asp.net

解决方案


中继器控件位于 ItemTemplate 内,因此您不能直接引用它们。您需要通过索引访问它们。

用你的方法你可以做到这一点

document.getElementById('<%= Repeater1.Items[i].FindControl("labelTotalCsrPercentage").ClientID %>').innerHTML = 
   document.getElementById('<%= Repeater1.Items[i].FindControl("txtInput").ClientID %>').value;

或者使用 jquery 时变得更容易。然后您可以使用nth-of-type选择器

$('#MyRepeater1 span:nth-of-type(2)').html($('#MyRepeater1 span:nth-of-type(2)').prev('input').val());

为此,您需要使用具有唯一 ID 的元素包装中继器

<span id="MyRepeater1">
    <asp:Repeater ID="Repeater1" runat="server">
    </asp:Repeater>
</span>

推荐阅读