我有一些jQuery代码,一次又一次地重复,我想减少我正在编写的代码,通过将其转换为函数.这是我正在使用的代码.
$('form#save-user button[name="save-user"]').click(function() {
var formData = 'option=saveuser&'+$('form#save-user').serialize();
$.ajax({
type: 'POST',url: 'process.PHP',data: formData,success: function(msg){
if(msg === 'empty') {
alert('required Values Missing');
} else if(msg === 'duplicateEmail'){
alert('Email already exist');
} else {
window.location = "index.PHP?users&option=edit&user_id="+msg+'&msg=success';
}
}
});
});
$('form#save-user button[name="save-user-close"]').click(function() {
var formData = 'option=saveuser&'+$('form#save-user').serialize();
$.ajax({
type: 'POST',success: function(msg){
if(msg === 'empty') {
alert('required Values Missing');
} else if(msg === 'duplicateEmail'){
alert('Email already exist');
} else {
window.location = 'index.PHP?users';
}
}
});
});
$('form#save-user button[name="save-user-new"]').click(function() {
var formData = 'option=saveuser&'+$('form#save-user').serialize();
$.ajax({
type: 'POST',success: function(msg){
if(msg === 'empty') {
alert('required Values Missing');
} else if(msg === 'duplicateEmail'){
alert('Email already exist');
} else {
window.location = 'index.PHP?users&option=create';
}
}
});
});
我想知道一些事情,
a) With reference to above code,how do i convert it to
function,as the code have very few changes like,selector name and
url of window.location.b) what do i call the code below,is it the function? function on
the go? or dynamic function?
$('selector').event(function(){
//jQuery Code in wake of event being triggered.
});
最佳答案
我会为它写一个小插件:
(function ($) {
jQuery.fn.myClick = function (destination) {
this.click(function () {
var formData = 'option=saveuser&'+$('form#save-user').serialize();
$.ajax({
type: 'POST',success: function(msg){
if(msg === 'empty') {
alert('required Values Missing');
} else if(msg === 'duplicateEmail'){
alert('Email already exist');
} else {
window.location = destination(msg);
}
}
});
});
}
}(jQuery));
然后调用它你只需:
$('form#save-user button[name="save-user-close"]').myClick(function() {
return 'index.PHP?users&option=create';
});
和
$('form#save-user button[name="save-user"]').myClick(function (msg) {
return "index.PHP?users&option=edit&user_id="+msg+'&msg=success';
});
你应该能够看到我们要去哪里;我们将参数添加到我们创建的小方法中,您可以在其中指定每次调用之间的更改.
因为在这个例子中,window.location依赖于AJAX响应(当我们调用函数时我们不知道响应!),我们不能简单地提供一个字符串(或类似的东西)作为参数.相反,我们传递一个我们在收到AJAX响应后调用的函数,前提是将msg作为变量;并依赖该函数提供我们设置为window.location的字符串.
至于你的第二个问题,你将一个事件处理程序传递给jQuery事件方法;一个事件处理程序将是一个函数引用(通常是对匿名函数的引用)