使用 jQuery 从 asp:Repeater 中删除项目

本文关键字:Repeater 删除项目 asp jQuery 使用 | 更新日期: 2023-09-27 18:35:31

如何从asp:Repeater中删除项目?目前,我有以下中继器代码:

<asp:Repeater ID="uxRolesList" runat="server">
    <ItemTemplate>                       
        <div id="<%# GetRolesDivId() %>">
            <asp:TextBox ID="uxTxtBoxRole" runat="server" rows="5" columns="100" Text='<%# Container.DataItem %>' TextMode="multiline" MaxLength="2000"></asp:TextBox>
            <asp:Button ID="uxRemoveRoleBtn" Style="vertical-align:top;" CssClass="remove-roles-btn" runat="server" Text="X" />
            <br />
            <asp:RequiredFieldValidator runat="server" ID="uxValTxtBoxRole" ControlToValidate="uxTxtBoxRole" ErrorMessage="Please complete this role requirement"></asp:RequiredFieldValidator>
            <br /><br />
        </div>
    </ItemTemplate>
</asp:Repeater>     

它应该输出如下内容:

<div id="roles-1">
    <textarea name="ctl00$mainContent$uxRolesList$ctl01$uxTxtBoxRole" rows="5" cols="100" id="ctl00_mainContent_uxRolesList_ctl01_uxTxtBoxRole">Quick test</textarea>                          <input type="submit" name="ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn" value="X" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_mainContent_uxRolesList_ctl01_uxRemoveRoleBtn" class="remove-roles-btn" style="vertical-align:top;" />
    <br />
    <span id="ctl00_mainContent_uxRolesList_ctl01_uxValTxtBoxRole" class="error" style="color:#891F11;display:none;">Please complete this role requirement</span>
    <br /><br />
</div>

我使用以下jQuery在单击删除按钮时"删除"该项目:

$("#roles-" + roleIdNumber).remove();
e.preventDefault();
rolesCounter--;

在本例中,roleIdNumber为 1。

但是当我提交表格时,该项目仍然出现 - 任何人都可以帮助我解决正在发生的事情吗?

使用 jQuery 从 asp:Repeater 中删除项目

我建议替换:

<div id="<%# GetRolesDivId() %>">

跟:

<div id="<%# GetRolesDivId() %>" class="div_row">

还有这一行:

<asp:Button ID="uxRemoveRoleBtn" Style="vertical-align:top;" CssClass="remove-roles-btn" runat="server" Text="X" />

跟:

<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" onclick="$(this).parents('.div_row').remove();rolesCounter--;" />

并删除您在此处共享的所有 js 代码。

希望它有帮助。

它可能不起作用,因为在 Document.Ready 函数调用完成执行后,中继器项被添加到 DOM 中。

如果您的转发器在页面加载完成后获取数据,请考虑使用 Jquery 的 on() 方法或委托方法。