3

I've got a division (<div>) which contains a form and I want to find out using jQuery if any of the <input>s have focus and if none of them have I want to call a function.

What is the best way of doing this?

Rough idea of div/form structure.

<div id="section1">
    <form ...>
       <input type="text" id="v1"> 
       <input type="text" id="v2">
       <input type="text" id="v3"> 
       <input type="text" id="v4">
       <input type="checkbox">
    </form>
</div>

Thanks.

4

2 回答 2

7

选择输入元素并过滤掉焦点元素:

$("#section1 input").filter(":focus")

应该为空,则所有元素都没有焦点。实际上,您有几种不同的选择方式来获得相同的结果。

if ($("#section1 input:focus").length === 0){
      callYourFunction();
}

因为 0 是一个假值,所以上面的 if 条件实际上是一样的:

if ( !$("#section1 input:focus").length )

请注意,尽管并不总是建议以这种方式检查虚假值。如果您以“正常”(第一种)方式编写它,通常会更好,更明显且不易出错。

于 2012-07-19T13:11:08.130 回答
2

您可以尝试如下:

$('input:focus')

将找出所有聚焦的输入元素。

if( !$('#section1 form input:focus').length ) {
  // do something if not focused element exists
  callFunction();
}

要找出不集中的输入:

$('#section1 form input:not(:focus)')
于 2012-07-19T13:18:29.497 回答