【问题标题】:hiding the link buttons when user leaves the text box当用户离开文本框时隐藏链接按钮
【发布时间】:2023-03-23 12:40:01
【问题描述】:

我的网页上有一个文本框和两个链接按钮。当我在文本框上添加一些值时,基于该值以及离开文本框时。我想隐藏或使链接按钮不可见。

<asp:textBox id="textBox1" runat="server">
 <asp:linkButton id="link1" runat="server">
 <asp:linkButton id="link2" runar="server">

当用户在文本框中输入值“X”时,我想隐藏 Link1 和 Link2,否则我希望 Link1 和 Link2 可见。

这是我的代码,但它不起作用:

function HidePick(selectObj) {    
       if (selectObj.value.toUpperCase() == "D9") {
        document.getElementById("LINK1").style.display = 'none';
    }
}

  <td><asp:TextBox ID="TXTTest1" runat="server" CssClass="cssTest" Width="30" onmouseout="javascript:HidePick(this);"

带有错误信息:

"JavaScript 运行时错误:无法获取未定义的属性 'style' 或空引用

【问题讨论】:

  • 你为什么不使用jquery? ... $("#link1").hide() 或 .toggle() api.jquery.com

标签: javascript asp.net


【解决方案1】:

对于这种 DOM 操作,使用 jQuery 很容易。

JS 小提琴 - https://jsfiddle.net/p8pm6r5r

<asp:TextBox ID="textBox1" runat="server" />
<asp:LinkButton ID="link1" runat="server" Text="Button1" />
<asp:LinkButton ID="link2" runat="server" Text="Button2" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">

    $(function() {
        $("#<%= textBox1.ClientID %>").blur(function () {
            if ($(this).val() === "X") {
                $("#<%= link1.ClientID %>").hide();
                $("#<%= link2.ClientID %>").hide();
            }
        });
    })
</script>

【讨论】:

  • 它没有要求jQuery,也没有带有jQuery的标签。
  • 它被标记为 ASP.Net。这些天在 ASP.Net 应用程序中看到 jQuery 并不少见。你给他一条鱼,我教他怎么钓鱼。
  • 还是站着,不求jQuery解决方案。
【解决方案2】:

在 asp.net 中,最终的渲染 ID 可能会在页面上发生变化,因此在 javascript 上您需要使用控件的 .ClientID... 您的代码必须为:

document.getElementById("<%=link1.ClientID%>").style.display = 'none';

相关:Accessing control client name and not ID in ASP.NET

【讨论】:

    【解决方案3】:
     <asp:textBox id="textBox1" runat="server">
    <asp:LinkButton ID="link1" runat="server" Text="Button1" />
    <asp:LinkButton ID="link2" runat="server" Text="Button2" />
    

    假设您不想使用 jQuery 或任何库;
    在 .aspx 页面中的 html 末尾添加一个脚本标记,以将按钮绑定到 mouseleavemouseout 事件。只是为了确保您的 textbox1 的 id 是静态的(它在源代码中的方式),一旦您的页面在浏览器上呈现,检查您的 textbox1 并查看它是否仍然具有相同的 id,如果没有,则复制该 id 并替换在从 textbox1 到 (whatever_textbox1) 的 javascript 代码的事件活页夹行下方。您的链接 ID 也是同样的步骤。

    document.getElementById("textBox1").addEventListener("mouseout",HidePick,false);
        function HidePick(e){
            if (e.target.value.toUpperCase() == "D9")
                 document.getElementById("LINK1").style.display = 'none';    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2014-07-14
      • 2011-09-13
      • 2015-04-19
      相关资源
      最近更新 更多