我有一个这样的 jQuery 函数:
$("input").focus(function () {
$(this).addClass('focus');
});
$("input").blur(function () {
$(this).removeClass('focus');
});
$("select").focus(function () {
$(this).addClass('focus');
});
$("select").blur(function () {
$(this).removeClass('focus');
});
$("textarea").focus(function () {
$(this).addClass('focus');
});
$("textarea").blur(function () {
$(this).removeClass('focus');
});
是否可以针对更少的代码进行优化?
最佳答案
$("input,select,textarea").focus(function() {$(this).toggleClass('focus')})
.blur(function() {$(this).toggleClass('focus')});
或
$("input,select,textarea").bind('focus blur',function() {$(this).toggleClass('focus')});
关于javascript - 请帮助优化简单的 JQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/810766/