jQuery:delegate中select()不起作用的解決方案(執行個體講解)_jquery

來源:互聯網
上載者:User

jQuery有一個很好用的delegate(事件委派)功能,可以給當前以及將來(動態添加)的元素繫結一個事件處理函數。

比如下面的例子,動態添加一個輸入文字框後,我想讓所有文字框(不管是不是動態添加的)在擷取焦點時,自動轉大寫。

複製代碼 代碼如下:

<!doctype html>
<html>
<head>
    <title>delegate測試</title>
 <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.js"></script>
 <style type="text/css">
*{padding:0;margin:0;list-style:none;margin:5px} 
 </style>

 <script type="text/javascript">
//動態添加一行文本輸入框
function addInput(){ 
 $("#ulTarget").append("<li><input type=\"text\" value=\"aaaaaa\"/></li>"); 
}


$().ready(function(){
 $("#ulTarget").delegate(":text","focus",function(){
$(this).val($(this).val().toUpperCase());
 }); 
})
 </script>
</head>
<body>
  <ul id="ulTarget">
 <li><input type="text" value="123456abc"/></li>
 <li><input type="text" value="123456abc"/></li>
 <li><input type="text" value="123456abc"/></li>
 <li><input type="text" value="123456abc"/></li>
  </ul>  
  <button id="btnAdd" onclick="addInput()">add input</button>
</body>
</html>


接下來,我還想加點小功能,在擷取焦點時,還要讓文字框自動全選。
複製代碼 代碼如下:

$().ready(function(){
 $("#ulTarget").delegate(":text","focus",function(){
$(this).val($(this).val().toUpperCase()).select();
 }); 
}) 

但是實際測下來,.select()死活就是不起作用,無奈請出setTimeout
複製代碼 代碼如下:

$().ready(function(){
 $("#ulTarget").delegate(":text","focus",function(){
var jqObj = $(this);
jqObj.val(jqObj.val().toUpperCase());
setTimeout(function(){jqObj.select();},100);
 }); 
}) 

解決了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.