jQuery Jquery关于焦点事件委托
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14063199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery on focus event delegation
提问by Linas
For some strange reason this simple function doesn't seem to work:
出于某种奇怪的原因,这个简单的函数似乎不起作用:
$("body").on("focus", this, function(){
alert('d');
})
this
is input or textarea element.
this
是 input 或 textarea 元素。
If i were to do this:
如果我要这样做:
$(this).on("focus", function(){
alert('d');
})
It would work on those elements that exists at the moment, but i event would not fire up on newly created elements, what am i doing wrong?
它适用于目前存在的那些元素,但我的事件不会在新创建的元素上触发,我做错了什么?
回答by grant
The second parameter is, as described by the API, "a selector string to filter the descendants of the selected elements that trigger the event."
第二个参数是,如 API 所述,“一个选择器字符串,用于过滤触发事件的所选元素的后代。”
I assume this
, in your case, is a DOM element. Try changing that to a selector to match inputs or textareas. This will cause your function to be called whenever a focus
event bubbles up to body
from an element matching your selector. This should work for you:
我假设this
,在你的情况下,是一个 DOM 元素。尝试将其更改为选择器以匹配输入或文本区域。这将导致您的函数在focus
事件body
从与您的选择器匹配的元素冒泡时被调用。这应该适合你:
$("body").on("focus", "input, textarea", function() {
alert('d');
});
Further information on on()
here: http://api.jquery.com/on/
有关on()
此处的更多信息:http: //api.jquery.com/on/
回答by Okan Kocyigit
As @grantman16 has mentioned that the second parameter must be a selector,
正如@grantman16 提到的,第二个参数必须是一个选择器,
But If it's a newly created element why don't you use focus().
但是如果它是一个新创建的元素,为什么不使用focus()。
?va?r input = $("<input>");
input.focus(function() {
alert('d');
});
$("body").append(input);?
?
You don't need to use .on
, but if you are insistent to use it, you should set a selector as second parameter,
你不需要使用.on
,但如果你坚持使用它,你应该设置一个选择器作为第二个参数,
var input = $("<input>").addClass("lastInput");
$("body").on("focus", "input.lastInput", function() {
alert('d');
});
$("body").append(input);
?
回答by axel.michel
You want something like this:
你想要这样的东西:
$(document).ready(function() {
$("body").on("focus", 'textarea, input', function(){
console.log('d');
})?
});