下面的代码在我的jquery的ready函数中工作得很好,当我填写表单并将焦点从input元素切换到另一个元素时,运行ajax检查并为该元素分配一个css类,显示是否经过验证。一切都很好。
我想用这段代码定义一个函数,这样我就可以在页面刚刚加载的时候调用它,所以如果表单是在服务器端填充的,在模糊的情况下也会执行检查,但我在jquery中定义函数时遇到了麻烦。
这是在blur上运行的代码
$('#join_username').blur(function(){
$('#join_username').addClass(\"join_form_input_checking\");
$('#join_username').removeClass(\"join_form_input\");
$('#join_username').removeClass(\"join_form_input_error\");
$('#join_username').removeClass(\"join_form_input_verified\");
$.post(\"inc/viewlets/join_form/check_username.php\", {
join_username: $('#join_username').val()
},
function(response){
setTimeout(\"finishAjaxUsername('usernameResult', '\"+escape(response)+\"')\", 400);
if(escape(response)=='true') joinFormCheck[0]=true;
else joinFormCheck[0]=false;
checkFormArray(joinFormCheck);
}
);
return false;
});发布于 2009-12-18 23:54:38
或者,您可以使用常规函数语法
function do_on_blur(){
// your base. I'm in it
}和
$("#join_username").blur( do_on_blur );发布于 2009-12-18 23:49:51
只需定义一个函数,而不是将匿名函数传递给blur():
$.myFunctionName = function()
{
// your code here
}
$("#join_username").blur($.myFunctionName);如果您希望调用函数以响应事件(如document.ready),只需像调用普通函数一样调用它即可。
$(document).ready(function()
{
// -- define your function
$.myFunctionName = function()
{
//your code here
}
// -- add a callback to blur on an input
$("#join_username").blur($.myFunctionName);
// -- manually call the function once
$.myFunctionName();
});发布于 2009-12-18 23:52:53
我认为这里的语法是无效的:
$('#join_username').blur( function(){
$(this)
.addClass("join_form_input_checking")
.removeClass("join_form_input");
.removeClass("join_form_input_error");
.removeClass("join_form_input_verified");
$.post("inc/viewlets/join_form/check_username.php", {
join_username: $(this).val()
}, function(response) {
setTimeout( function() {
finishAjaxUsername('usernameResult', escape(response))
}, 400);
if(escape(response)=='true') { joinFormCheck[0]=true; }
else { joinFormCheck[0]=false; }
checkFormArray(joinFormCheck);
} );
return false;
} );试试看。当然,如果你想把这个函数从blur事件中分离出来,你可以简单地把它赋给一个变量……所以你最终会得到:
var blurFunc = function() { ...function from above... };
$('#join_username').blur( blurFunc );https://stackoverflow.com/questions/1928949
复制相似问题