使用jQuery时可以在UpdatePanel中放置控件吗?

时间:2012-09-28 19:33:26

标签: jquery asp.net

使用这个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();         });

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

2 个答案:

答案 0 :(得分:2)

更新面板中的内容更新后,元素将替换为没有事件绑定的新元素。

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

对于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();
});

答案 1 :(得分:1)

您必须使用liveon注册click事件,因为您在ajax调用中取消绑定了点击事件。 liveon jquery方法确保在将元素添加到DOMlive选择器下的on时重新绑定事件。你的jquery版本很老,你需要升级它可能是1.7.2

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