Javascript/jQuery: Why is the focus event not firing on an input field?
I'm trying to attach a simple focus/blur event listener via the .live()
jQuery method to my inputs but what I'm noticing is that the focus
event is not firing whereas the blur
开发者_如何学Pythonevent is.
Strange… was hoping you may have an idea of why this is happening.
Here is the code:
function rowHighlight() {
var form = $('form.register'),
ele = {};
form.find('label').each(function(i) {
var link = this.htmlFor;
form.find('label[for='+link+'],input[name='+link+'],textarea[name='+link+']').wrapAll('<span class="row"/>');
});
ele.row = $('form > .row');
ele.inputs = ele.row.find('input');
$.each(ele.inputs, function(i) {
$(this).focus(function() {
console.log('hello'); // this will fire.
});
$(this).live('focus blur', function(e) {
console.log('current event type: '+e.type); // the focus on this will not fire!?
( e.type=='focus' ? console.log('focussed') : console.log('blurred') )
});
});
}
rowHighlight();
$(this).focus…
was just put it as a debugging thing and removing it does not make the focus
on the live
listener work…
Any help would be appreciated.
Thanks for stopping by.
Jannis
Try changing this line:
$.each(ele.inputs, function(i) {
to this line:
ele.inputs.each(function() {
Explanation:
There are two forms of each()
in jQuery.
Iterating over a map or array:
$.each([1,2,3], function(index, value){
});
or, when iterating over a jQuery object:
$("a").each(function(){
});
http://api.jquery.com/jQuery.each/
$(this)
means what you would expect only in the second use:
$("a").each(function(){
$(this).remove();
});
Live vs. Bind:
$("a").click(someClickEventHandler);
... binds the someClickEventHandler
click event handler to every a
tag that exists when this is executed.
$("a").live("click", someClickEventHandler);
... binds the someClickEventHandler
click event handler to every a
tag that exists when this is executed, AND it will also bind the someClickEventHandler
click event handler to every a
event that will ever exist. For example, if an a
tag is created from an Ajax response, the event handler will automatically be bound.
精彩评论