0

使用此 jQuery 代码,我试图在单击时选择控件内的文本。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">

        jQuery(document).ready(
            function () {
                jQuery("input[type='text']").click(function () {
                    this.select();
                });
            });  

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox Text="Text 1" ID="txt1" ClientIDMode="Static" runat="server" />
        <asp:Button Text="Submit" ID="btn1" OnClick="btn1_Click" runat="server" />
        <asp:TextBox Text="Text 2" ID="txt2" ClientIDMode="Static" Visible="false" runat="server" />
    </div>
    </form>
</body>
</html>

代码背后:

protected void btn1_Click(object sender, EventArgs e)
    {
        txt2.Visible = true;
    }

问题是当我将页面内容放入 UpdatePanel 时,jQuery 第一次在 txt1 上运行。单击按钮时,它不适用于任何文本框。

    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:TextBox Text="Text 1" ID="txt1" ClientIDMode="Static" runat="server" />
            <asp:Button Text="Submit" ID="btn1" OnClick="btn1_Click" runat="server" />
            <asp:TextBox Text="Text 2" ID="txt2" ClientIDMode="Static" Visible="false" runat="server" />
</ContentTemplate>
    </asp:UpdatePanel>

在使用 Chrome 控制台进行调试时,我发现 jQuery 没有定义 - 奇怪 :-( 你能建议可能出现的问题吗?

感谢您的时间。

编辑:根据您的回复,我尝试遵循这些解决方案,对我来说都很好。

将事件绑定到 form1,并将其包含在准备好的文档中。

> jQuery(document).ready(
>       function () {
>           jQuery("#form1").on("click", "input[type='text']", function () {
>               this.select();
>           });
>       });

将事件绑定到文档本身 -

jQuery(document).on("click", "input[type='text']" ,function () { this.select(); });

第一个对我来说似乎更安全,性能更高,你有什么建议?

4

2 回答 2

2

当更新面板中的内容更新时,这些元素将被替换为没有事件绑定的新元素。

您需要使用委托而不是将事件绑定到元素本身。将其绑定在更新面板周围的元素上,以便在更新面板中的内容被替换后处理事件:

对于 jQuery 1.4.2 及更高版本:

jQuery("#form1").delegate("input[type='text']", "click", function () {
  this.select();
});

对于 jQuery 1.7 及更高版本:

jQuery("#form1").on("click", "input[type='text']", function () {
  this.select();
});
于 2012-09-28T19:44:36.853 回答
1

You have to use live or on for registering click event as click event you have is un-binded on ajax call. live or on jquery method ensure the event is re-binded as the element is added to DOM which comes under live or on selector. Your jquery version is quite old you need to upgrade it might be 1.7.2

jQuery(document).ready(
      function () {
            jQuery(document).on("click", "input[type='text']", function () {
            this.select();
       });
});  
于 2012-09-28T19:45:38.420 回答