【问题标题】:Why the "focusin" event handler isn't called?为什么不调用“focusin”事件处理程序?
【发布时间】:2010-10-28 05:12:11
【问题描述】:

为什么在following code 中没有调用focusin 事件处理程序?

HTML:

<div id='wrapper'></div>
<div id='button'>Click Here</div>
<div id='output'></div>

JS:

$(function() {
    $('input').live('focusin', function() {
        $('#output').html('focusin'); // Why this not happens ?
    });
    $('#button').click(function() {
        $('#button').hide();
        build_inputs();
    });    
});
function build_inputs() {
    var html = "<input type='text' /> \
                <br /> \
                <input type='text' />";
    $('#wrapper').append(html);
    $('#wrapper').fadeIn(500, function() {
        $('input:first').focus();
    });
}

CSS:

#wrapper {
    display: none;
    background: #aaa;
    width: 170px;
    padding: 20px;
}

【问题讨论】:

  • 我对您要做什么感到困惑?附加输入后它对我有用。
  • 除非你在谈论它,否则在fadeIn 之后不要专注于尝试$("input:first").focus().focusin();

标签: javascript html jquery jquery-events focusin


【解决方案1】:

出于某种原因,我不确定为什么.focus() 不会触发focusin 事件。

您可以通过更改焦点线以添加 .trigger('focusin') 来复制此行为。

所以你的 fadeIn 代码变成:

$('#wrapper').fadeIn(500, function() {
    $('input:first').focus().trigger('focusin');
});

你可以在这里测试它:http://jsfiddle.net/yt7Jd/

编辑:正如 Jason 所说,您也可以调用 .focusin() 方法而不是 .trigger('focusin')。

编辑 2:这似乎是 1.4.3 中的一个错误。它已被 jQuery 团队记录以进行修复:http://bugs.jquery.com/ticket/7340

【讨论】:

  • 他也可以致电.focusin(),正如我在上面的评论中提到的那样。
  • @Jason:他确实可以。有趣的是,.focusin() 的文档并没有这样说。
  • 谢谢!但我仍然想知道为什么focus() 不会触发focusin 事件。这是已知行为吗?
  • @Misha:这似乎是 jQuery 1.4.3 中的一个错误。如果您转到我制作的 jsfiddle,请删除 .trigger(),将 jquery 版本更改为 1.4.2,然后您的代码将按预期工作。
  • 哇,难以置信!我刚从 1.4.2 搬到 1.4.3 :) 非常感谢!
猜你喜欢
  • 2020-03-06
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多