jQuery模糊()不工作?
完全被这里难住了。 尝试一些非常简单的东西,但它不起作用:
$("input.input1, textarea.input1").focus(function(){ $(this).addClass("input2").removeClass("input1"); }); $("input.input2, textarea.input2").blur(function(){ $(this).addClass("input1").removeClass("input2"); });
基本上模糊不会发射。 我点击输入框,框就会改变。 我点击了框,没有任何反应。 任何帮助都会很棒。
您需要使用委托处理程序,因为在应用处理程序时输入没有类input2
。
$(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'); });
但是,可能有更好的方法来做到这一点。 我建议使用第三个类来标记需要切换类的输入,然后在事件发生时切换类。
$('.needsToggle').on('focus blur', function() { $(this).toggleClass('input1 input2'); });
如果他们总是有类input1
来启动,你可以使用它而不是needsToggle
。
因为您正在影响相同的元素,所以链接更容易:
$("input.input1, textarea.input1").focus(function(){ $(this).addClass("input2").removeClass("input1"); }).blur(function(){ $(this).addClass("input1").removeClass("input2"); });
JS小提琴演示 。
至于为什么你的jQuery不能正常工作,我不确定,我害怕; 虽然我怀疑它与选择器有关。
试试这段代码:
$("input.input1, textarea.input1").bind('focus blur', function(){ $(this).toggleClass("input2").toggleClass("input1"); });
如果它不起作用,您可能需要使用focusout
而不是blur
:
$("input.input1, textarea.input1").bind('focus focusout', function(){ $(this).toggleClass("input2").toggleClass("input1"); });
如果你在jQuery <1.7上,你需要使用.delegate()
。
和.on()
如果你在1.7或更高。
不要使用.live()
因为它更慢。
此外,如果你的元素加载ajax使用$(document).on(事件,选择器,函数),因为标准例如。 $(selector).click(function()…不起作用