简体   繁体   中英

jQuery .blur .focus not Working in Test

When writing a jasmine test, it appears that jQuery doesn't recognize that an input has focus. When changing between the two input elements, the alert isn't shown and when clicking out of the inputs without focusing the other one the alert is shown. However, by using .focus and .blur in my test code, I can't get the desired behaviour. It always thinks that none of them are focused. Also without calling .triggerHandler , the blur handler isn't invoked at all.

The inputs are visible and are attached to the DOM.

var $inputs = $("input");
function blurTimeout() {
  if (!$inputs.is(":focus")) {
    alert("Nothing's focused");
  }
}

function blur() {
  setTimeout(blurTimeout, 0);
}

function main() {
  $inputs.on("blur", blur);
}
$(main);

jsfiddle

Edit It would appear that calling $inputs.first().focus() to focus one of the inputs, then alert($inputs.first().is(":focus")) alerts false .

var $input = $inputs.first();
$input.focus();
alert(!!$input.is("focus")); // -> false

The events and handlers seem to fire just fine. The problem is the logic. When any of the inputs has focus !$inputs.is(':focus') always returns false . You can resolve that by replacing:

!$inputs.is(':focus')

With:

$inputs.filter(':focus').length

DEMO

Below is the changed code. Testing now works as intended and the original behaviour is kept.

var $inputs = $("input");
function blurTimeout() {
    var index = $inputs.length;
    while(index--){
        if($inputs[index] === document.activeElement){
            return;
        }
    }
    alert("Nothing's focused");
}

function blur() {
    setTimeout(blurTimeout, 0);
}

function main() {
    $inputs.on("blur", blur);
}
$(main);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM