我有一个 ascx 调用 ProductSearch

在 ascx 我有这 4 个控件

<asp:TextBox runat="server" ID="txtSearchProduct" type="text" class="form-control typeahead" data-provide="typeahead" autocomplete="off">
</asp:TextBox>
<asp:TextBox runat="server" ID="txtProductNames" CssClass="hidden">
</asp:TextBox>
<asp:TextBox runat="server" ID="txtSearchProductID" Style="display: none;">
</asp:TextBox>
<asp:TextBox runat="server" ID="txtCaricati" Style="display: none;">
</asp:TextBox>

在这个 ascx 中,我有一个 javascript 函数,它用所有可能的值填充预先输入的文本框:
function LoadProducts() {
    var data = $("#<%=txtProductNames.ClientID%>").val();

    var $input = $(".typeahead");
    var jsonObj = $.parseJSON(data);
    var sourceArr = [];
    for (var i = 0; i < jsonObj.length; i++) {
        sourceArr.push(formatRow(jsonObj[i].id, jsonObj[i].code, jsonObj[i].name));
    }

    // init Typeahead
    $input.typeahead({
        ...
    }

现在,问题是我有一个需要两次实现 ascx 的 aspx 页面。
一个在主要 div 中,一个在模态 div 中(由 html 隐藏,而模态不可见)。

使用 F12 工具探索 html 我发现我两次使用相同的函数 LoadProducts()。

在第一个函数中,该函数与它的 ClientId 对象一起工作,第二个也是。

我从后面的代码中调用了函数 LoadProducts() 并执行了代码中找到的第一个函数,也许是错误的。

我需要一种方法来根据我使用的 ascx 实例来识别 javascript 函数。

有没有办法做到这一点?如果我还不够清楚,请问我问题。

最佳答案

如果您不想要“全局”LoadProducts,这会好得多,您需要使每个 javascript 函数都是唯一的。
为此,您可以使用用户控件本身的 ID。

所以你可以在 ascx 里面做这个

<script>
    function LoadProducts_<%= this.ID %>() {
        alert('Products Loaded.')
    }

    LoadProducts_<%= this.ID %>();
</script>

因此,如果您有 2 个这样的用户控件
<uc1:WebUserControl1 ID="WebUserControl1" runat="server" />
<uc1:WebUserControl1 ID="WebUserControl2" runat="server" />

您将拥有这样的 javascript 函数
function LoadProducts_WebUserControl1() {

}

关于javascript - 同一页面上的更多 ascx 实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56869427/

10-11 13:33