2012-09-28 30 views
0

有了這個jQuery代碼,我試圖選擇控制,點擊后里面的文字。使用jQuery時可以在UpdatePanel中放置控件嗎?

<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的(文件)。在( 「點擊」, 「輸入[類型= '文本']」,函數(){ this.select(); });

第一個對我來說似乎更安全,性能更高,您有什麼建議?

+0

我想在這裏你的問題的解決方案http://stackoverflow.com/questions/2313882/javascript-object-is-not-defined -error-after-scriptmanager-registerclientscrip –

回答

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(); 
}); 
+0

我試過1.7。看起來它是強制性的將你的代碼包裝在$(document).ready中。我對麼 ? – Abhijeet

+0

@autrevo:是的。我只是顯示了綁定委託的代碼。 – Guffa

+0

謝謝。更新的問題中哪個版本似乎具有更大的性能優勢? – Abhijeet

1

你必須使用liveon登記click事件,你有點擊的事件是未綁定的ajax調用。 liveon jquery方法確保事件被重新綁定,因爲元素被添加到DOM,該屬性位於liveon選擇器中。您的jQuery的版本是很舊,需要更新它可能是1.7.2

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