我有這個jQuery的事件處理程序代碼,我想將它轉換成一個功能這個jQuery函數有什麼問題?
$("#activate-user").click(function() {
var userId = [];
$(':checkbox:checked').each(function(i) {
userId[i] = $(this).val();
});
if(userId.length == 0) {
//If userId is empty
} else {
$.ajax({
type: 'POST',
url: 'process.php',
data: 'option=activate&userId='+userId,
success: function(msg){
if(msg == 0) {
//If cannot process the query.
} else {
//If query is processed.
location.reload(true);
}
}
});
}
});
$("#block-user").click(function() {
var userId = [];
$(':checkbox:checked').each(function(i) {
userId[i] = $(this).val();
});
if(userId.length == 0) {
//If userId is empty
} else {
$.ajax({
type: 'POST',
url: 'process.php',
data: 'option=block&userId='+userId,
success: function(msg){
if(msg == 0) {
//If cannot process the query.
} else {
//If query is processed.
location.reload(true);
}
}
});
}
});
這兩個事件處理程序之間的唯一區別是,即option=
data: 'option=activate&userId='+userId
data: 'option=block&userId='+userId
值
我想這個把它轉換成jQuery函數N代表我試圖做這樣它完全不工作,
(function ($) {
jQuery.fn.userOperation = function(opString) {
this.click(function() {
var userId = [];
$(':checkbox:checked').each(function(i){
userId[i] = $(this).val();
});
if(userId.length === 0) {
//If userId is empty.
} else {
$.ajax({
type: 'POST',
url: 'process.php',
data: 'option='+opString+'&userId='+userId,
success: function(msg){
if(msg == 0) {
//If cannot process the query.
} else {
//If query is processed.
location.reload(true);
}
}
});
}
});
}
}(jQuery));
jQuery的函數調用:
$('#activate-user').userOperation(function() {
return 'block';
});
這似乎並不工作,因爲我沒有正確地傳遞參數給函數,因爲我是jQuery的新手,我不知道如何做到這一點。我哪裏錯了?這是將參數傳遞給jQuery函數的正確和可行的方法?
謝謝你..
大部分的代碼看起來外國人對我來說:D,我很抱歉,但我是jQuery的新手,我會很感激,如果你可以擴大你的幫助,解釋我到底是怎麼回事:) –
@ibrahim:I只是爲你評論它。 ;-) –
那真是太好了,謝謝:) –