【问题标题】:jquery .live 'focus' event not being triggered on google chrome谷歌浏览器上未触发 jquery .live 'focus' 事件
【发布时间】:2012-04-21 19:08:15
【问题描述】:

我想知道这是 chrome 或 jQuery 中的错误,还是我误解了 .live 函数的用法

$('.input_form input[type="radio"]').live({
    'change':function(){
        console.log("this is a radio button");
    }
});

当我在所有主要浏览器中单击类“input_form”的单选按钮时,上面的代码会将输出发送到控制台窗口

但是下面的代码:

$('.input_form input[type="radio"]').live({
    'focus':function(){
        console.log("this is a radio button");
    }
});

将输出发送到所有浏览器中的控制台窗口,除了 google chrome (10)

唯一的区别是我的事件触发器从“更改”变为“焦点”。

谁能解释一下?

【问题讨论】:

    标签: google-chrome jquery browser-support


    【解决方案1】:

    如果使用 jQuery 1.7+,你可能应该这样做:

    $(document).on({
        change: function(){
            console.log("this is a radio button on change");
        },
        focus: function() {
            console.log("this is a radio button on focus");
        }
    }, '.input_form input[type="radio"]');
    

    如果仍在使用直播,并且不需要地图,请执行以下操作:

    $('.input_form input[type="radio"]').live('focus', function(){
        console.log("this is a radio button");
    });
    

    或者用地图:

    $('.input_form input[type="radio"]').live({
        focus: function(){
            console.log("this is a radio button");
        }
    });
    

    在 webkit 中,只有在使用选项卡时才会自动单击单选按钮。 但是,您可以将焦点设置在元素上,尽管您为什么要这样做超出了我的理解,但这是可能的:

    $(document).on({
        click: function(){
            console.log("this is a radio button on click");
            $(this).focus();
        },
        focus: function() {
            console.log("this is a radio button on focus");
        }
    }, '.input_form input[type="radio"]');
    

    FIDDLE

    【讨论】:

    • 升级到 1.7 并尝试了所有三种解决方案,但仍然无法在 chrome 中触发“焦点”。在您的第一个解决方案中,“这是无线电变化”被写入控制台,而不是 chrome 中的“这是无线电焦点”,在 Firefox 中,两个句子同时记录
    • @KevinBradshaw - 更新了我的答案,但我相信 Mirko 更快。
    • 接受了 Mirko 的回答,并为你的内容如此丰富而点赞
    【解决方案2】:

    检查这个问题 [1],它指出焦点事件不会在 chrome 和 safari 中的单选按钮上触发。

    [1]https://stackoverflow.com/a/5744926/1317080

    【讨论】:

      【解决方案3】:

      我不确定,但我认为您必须使用 focusin 而不是 focus

      $('.input_form input[type="radio"]').live({
          'focusin': function(){
              console.log("this is a radio button");
          }
      });
      

      至少在一段时间之前,focusin 是处理livefocus 的标准化事件。

      blur 被称为focus out


      注意:

      focusin 事件在元素或其中的任何元素获得焦点时发送到该元素。这与焦点事件的不同之处在于它支持检测父元素上的焦点事件(换句话说,它支持事件冒泡)。

      【讨论】:

      • 感谢您的回答,但更改为 focusin 对 Chrome 没有影响
      猜你喜欢
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      相关资源
      最近更新 更多