js/jquery 即時監聽輸入框值變化的完美方案:oninput & onpropertychange

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

本文轉載於 http://blog.163.com/lgh_2002/blog/static/44017526201341511112874/

 

  Jquery綁定事件(bind和live的區別)   js/jquery 即時監聽輸入框值變化的完美方案:oninput & onpropertychange js/jquery 即時監聽輸入框值變化的完美方案:oninput & onpropertychange  

2013-05-15 11:01:12|  分類: jquery/javascrip |  標籤: |舉報 |字型大小大中小 訂閱

    (1)     先說jquery, 使用 jQuery 庫的話,只需要同時綁定 oninput 和 onpropertychange 兩個事件就可以了,範例程式碼: $(‘#username‘).bind(‘input propertychange‘, function() {     $(‘#content‘).html($(this).val().length + ‘ characters‘); }); (2)  對於JS原生寫法而言, oninput 是 HTML5 的標準事件,對於檢測 textarea, input:text, input:password 和 input:search 這幾個元素通過使用者介面發生的內容變化非常有用,在內容修改後立即被觸發,不像 onchange 事件需要失去焦點才觸發。oninput 事件在主流瀏覽器的相容情況如下:

 

  

  從上面表格可以看出,oninput 事件在 IE9 以下版本不支援,需要使用 IE 特有的 onpropertychange 事件替代,這個事件在使用者介面改變或者使用指令碼直接修改內容兩種情況下都會觸發,有以下幾種情況:

  • 修改了 input:checkbox 或者 input:radio 元素的選擇中狀態, checked 屬性發生變化。
  • 修改了 input:text 或者 textarea 元素的值,value 屬性發生變化。
  • 修改了 select 元素的選中項,selectedIndex 屬性發生變化。

  在監聽到 onpropertychange 事件後,可以使用 event 的 propertyName 屬性來擷取發生變化的屬性名稱。

  集合 oninput & onpropertychange 監聽輸入框內容變化的範例程式碼如下:

 

 1 <head> 2  3     <script type="text/javascript"> 4     // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9 5         function OnInput (event) { 6             alert ("The new content: " + event.target.value); 7         } 8     // Internet Explorer 9         function OnPropChanged (event) {10             if (event.propertyName.toLowerCase () == "value") {11                 alert ("The new content: " + event.srcElement.value);12             }13         }14     </script>15 </head>16 <body>17     Please modify the contents of the text field.18     <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />19 </body>

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.