簡體   English   中英

jQuery:函數形式的.blur(),而不是元素

[英]Jquery: function on .blur() of form, not elements

我在社區中進行了搜索,發現有很多關於如何為表單元素制作on(blur(function))或on(focusout(function))的指南,但是我沒有看到何時出現模糊元素表單本身會失去焦點。 我希望這種行為依賴於在提交之前更新兩個字段,但是如果我在onblur()字段上有效,則會出現錯誤錯誤,因為用戶沒有機會更新另一個字段。

這是我基本概念的代碼:

 $(document).ready(function(){ $("form").blur(function(){ alert("This form has lost its focus."); }); }); 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <form> Enter your name: <input type="text"> Enter your age: <input type="text"> </form> <p>Write something in the input field, and then click outside the field to lose focus (blur).</p> </body> </html> 

如果我將.ready語句的重點放在“輸入”上, 那么它可以正常工作 ,但是當我希望文檔監視整個表單時, 完全沒有響應。 有任何想法嗎? 謝謝!

您正在尋找的事件不會blur它的focusout 如果我們將focusout事件綁定到表單本身,則當焦點在表單內的任何元素上丟失時,將調用處理程序。

還要注意,我添加到各種元素中的tabindex屬性與此代碼的工作無關。 之所以添加它們,是因為您對帖子發表了錯誤的評論,聲稱表單無法集中顯示。

從這里tabindex

tabindex全局屬性指示其元素是否可以聚焦,以及是否/在何處參與順序鍵盤導航(通常使用Tab鍵,因此使用名稱)。 它接受一個整數作為值,根據該整數的值,結果會有所不同:

  • 負值(通常為tabindex =“-1”)意味着該元素應該是可聚焦的,但不能通過順序鍵盤導航來訪問。 在使用JavaScript創建可訪問的窗口小部件時最有用。

如您所見,任何元素都可以得到關注。 只是默認情況下,只有某些元素(焦點,輸入,按鈕等) 獲得焦點,而無需為其設置tabindex 在下面的示例中,如果單擊“輸入您的姓名”文本,您將看到表單本身獲得了焦點。 然后,您可以制表到輸入,然后是div,最后是跨度。 他們都依次受到關注。

 $('#theForm').on('focusout', function(e) { // do what you want/need to do here console.log('Form has lost focus'); }); 
 #theDiv { height: 50px; width: 50px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="theForm" tabindex="1"> Enter your name: <input type="text" tabindex="2"> Enter your age: <input type="text" tabindex="3"> </form> <div id="theDiv" tabindex="4"></div> <span tabindex="5">Some Text</span> <p>Write something in the input field, and then click outside the field to lose focus (blur).</p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM