如何使焦点事件发生在动态插入的输入上?
How can I make focus event happened on the dynamically inserted input?
$("input").focus(function(){
console.log('input focused');
});
上面是我测试焦点事件的代码 happened.And 我做了一个按钮来插入另一个输入 dynamically.But 当我聚焦插入的输入时,根本没有控制台记录。
有人可以帮忙吗?
谢谢
你需要使用 event delegation with the focusin event as 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>
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 中不在视口中的下一个输入。所以我在上面写了一个函数来绑定插入的输入来告诉。但阿伦的回答也有效。非常感谢。
$("input").focus(function(){
console.log('input focused');
});
上面是我测试焦点事件的代码 happened.And 我做了一个按钮来插入另一个输入 dynamically.But 当我聚焦插入的输入时,根本没有控制台记录。
有人可以帮忙吗?
谢谢
你需要使用 event delegation with the focusin event as 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>
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 中不在视口中的下一个输入。所以我在上面写了一个函数来绑定插入的输入来告诉。但阿伦的回答也有效。非常感谢。