$('.search-input').focus(function () {
$(this).val('');
});
$('.search-input').blur(function () {
if ($(this).val() == '') {
$(this).val('enter the place');
}
});
$('#edit-name').keyup(function () {
if ($(this).val() != '') {
$('.username .error-message').remove();
} else {
$('#edit-name').after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});
$('#edit-name').blur(function () {
if ($(this).val() == '') {
$('.username .error-message').remove();
$('#edit-name').after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});
$('#edit-pass').keyup(function () {
if ($(this).val() != '') {
$('.password .error-message').remove();
} else {
$('#edit-pass').after('<span style="color:red;" class="error-message"> enter the password!</span>');
}
});
$('#edit-pass').blur(function () {
if ($(this).val() == '') {
$('.password .error-message').remove();
$('#edit-pass').after('<span style="color:red;" class="error-message" >enter the password!</span>');
}
});有没有合并或美化代码的方法?谢谢。
发布于 2012-11-01 11:40:28
jQuery最好的功能之一是链接,在这个功能中,你可以用一个选择器来放置多个事件。因此,您可以像这样简单地使用前两个函数:
$('.search-input').focus(function(){
$(this).val('');
}).blur(function(){
if($(this).val()==''){
$(this).val('enter the place');
}
});另一种选择是将所有这些都放在事件映射下,如下所示:
$('.search-input').on({
focus: function(){
$(this).val('');
}, blur: function(){
if($(this).val()=='') $(this).val('enter the place');
}
});如果你有相同的函数但是有多个事件,你可以通过使用.bind或.on (这是更好的选择),然后将所有的事件添加到一个事件中,来一次绑定所有的事件。然后,如果您想要选择多个元素,也可以通过在选择器中用逗号分隔它们来实现。您可以使用$(this)引用相关元素。
$('#edit-name, #edit-pass').on('keyup blur', function(){
if($(this).val()!=''){
$('.username .error-message').remove();
}else{
$(this).after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});所以你看,你真的只需要两个函数,而不需要一遍又一遍地复制相同的东西。
发布于 2012-11-01 11:39:07
您可以在每个选择器中选择多个元素,并使用this引用为其触发事件的特定元素。
示例:
$("#foo, #bar").keyup(function() {
$(this).after('a');
});当你在#foo或#bar上设置关键字时,它会在那个元素后面添加a。
使用此技术,您可以将两个关键帧和模糊块分别合并为一个。
另一件事是链接事件:
$("#foo, #bar").keyup(function() {
$(this).after('a');
}).blur(function(){
$(this).after('b');
});这对快捷键和模糊事件使用相同的选择器。
Here's a demo
发布于 2012-11-01 11:39:56
利用jquery的链接。不需要双击。
例如:
$('.search-input').focus(function(){
$(this).val('');
}).blur(function(){
if( $(this).val()=='' ){
$(this).val('enter the place');
}
});您也可以对其他用户执行此操作。
尽可能使用$(this):
$('#edit-name').blur(function(){
if( $(this).val()=='' ){
$('.username .error-message').remove();
-->>>$(this).after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});https://stackoverflow.com/questions/13170553
复制相似问题