简体   繁体   English

jQuery .blur .focus无法在测试中工作

[英]jQuery .blur .focus not Working in Test

When writing a jasmine test, it appears that jQuery doesn't recognize that an input has focus. 编写茉莉花测试时,jQuery似乎无法识别输入具有焦点。 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. 但是,通过在测试代码中使用.focus.blur ,我无法获得所需的行为。 It always thinks that none of them are focused. 它总是认为它们都不是重点。 Also without calling .triggerHandler , the blur handler isn't invoked at all. 同样,在不调用.triggerHandler ,根本不会调用模糊处理程序。

The inputs are visible and are attached to the DOM. 输入是可见的,并已附加到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 jsfiddle

Edit It would appear that calling $inputs.first().focus() to focus one of the inputs, then alert($inputs.first().is(":focus")) alerts false . 编辑看来,调用$inputs.first().focus()来聚焦其中一个输入,然后alert($inputs.first().is(":focus"))警告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 . 当任何输入具有焦点时, !$inputs.is(':focus')始终返回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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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