【问题标题】:How can I make focus event happened on the dynamically inserted input?如何使焦点事件发生在动态插入的输入上?
【发布时间】:2016-02-26 05:08:23
【问题描述】:
$("input").focus(function(){
    console.log('input focused');
});

上面是我测试焦点事件是否发生的代码。我制作了一个按钮来动态插入另一个输入。但是当我关注插入的输入时,根本没有控制台记录。

有人可以帮忙吗?

谢谢

【问题讨论】:

  • 在读到您`制作了一个按钮以动态插入另一个输入'后,我希望有一个

标签: javascript jquery dom focus


【解决方案1】:

您需要将event delegationfocusin 事件一起使用,因为focus 不支持冒泡(事件委托需要冒泡支持才能工作)。

$("input").focus(function() {
  snippet.log('input focus: ' + $('input').index(this));
});

$('#dynamicarea').on('focusin', 'input', function() {
  snippet.log('input focusin: ' + $('input').index(this));
});

$('button').click(function() {
  $('div').append('<input />');
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<br />
<button>Add</button>
<div id="dynamicarea"></div>

【讨论】:

  • 感谢您的链接。我已经删除了误导性的答案。感谢您没有否决答案:)
【解决方案2】:
 function focused(evt){
    var target = evt.target;
    var target_name = evt.target.nodeName;
    $(target).keydown(function(e){
        if(e.which==9 && $(e.target).parent().parent().is(":last-of-type")){
            e.preventDefault();
        }else{
            $(this).unbind("keydown");
        }
    });
}
<sectionA>
<input>
/*insert input here*/
</sectionA>
<sectionB>
<input>
<input>
</sectionB>

最初我试图停止关注 sectionB 中的下一个输入,该输入在按下选项卡时不在视口中。所以我在上面写了一个函数来绑定在插入的输入中告诉。但阿伦的回答也有效。非常感谢。

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多