问题
Totally stumped here. Trying something pretty easy, but it's not working:
$("input.input1, textarea.input1").focus(function(){
$(this).addClass("input2").removeClass("input1");
});
$("input.input2, textarea.input2").blur(function(){
$(this).addClass("input1").removeClass("input2");
});
Basically the blur isn't firing. I click on the input box and the box changes. I click away from the box and nothing happens. Any help with this would be awesome.
回答1:
You need to use a delegated handler as the input doesn't have class input2
at the time the handler is applied.
$(document).on('focus','input.input1, textarea.input1', function() {
$(this).addClass('input2').removeClass('input1');
});
$(document).on('blur','input.input2, textarea.input2', function() {
$(this).addClass('input1').removeClass('input2');
});
There are probably better ways to do this, however. I'd suggest using a third class to mark the inputs that need the class toggled, then just toggle the classes when the event occurs.
$('.needsToggle').on('focus blur', function() {
$(this).toggleClass('input1 input2');
});
If they always have class input1
to start, you could use that instead of needsToggle
.
回答2:
Because you're affecting the same elements, it's somewhat easier to chain:
$("input.input1, textarea.input1").focus(function(){
$(this).addClass("input2").removeClass("input1");
}).blur(function(){
$(this).addClass("input1").removeClass("input2");
});
JS Fiddle demo.
As to why your jQuery isn't working as-is, I'm unsure, I'm afraid; though I suspect it's to do with the selectors.
回答3:
Try this code:
$("input.input1, textarea.input1").bind('focus blur', function(){
$(this).toggleClass("input2").toggleClass("input1");
});
If it does not work, you might need to use focusout
instead of blur
:
$("input.input1, textarea.input1").bind('focus focusout', function(){
$(this).toggleClass("input2").toggleClass("input1");
});
回答4:
You need to use .delegate() if you are on jQuery < 1.7.
And .on() if you are on 1.7 or greater.
Don't use .live()
since it is waaaaay slower.
回答5:
Also if your elements loaded with ajax use $(document).on(event,selector,function) , because standart eg. $(selector).click(function() ... will not work
来源:https://stackoverflow.com/questions/8290180/jquery-blur-not-working