2012-12-13 56 views
0

我有三個按鈕的塊,每個按鈕加載不同的內容。 如何將這三個幾乎相同的函數縮短爲一個函數?縮短功能於一體

$('#mega_online').click(function() { 

     $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
     $("#contentjq").load("http://site.com/online.php?more=" + $morenum + "&movies=1"); 
     $("#contentjq_more").empty().html(''); 
    $morenum = $morenum+20; 
     $("#contentjq").show(); 

}); 

$('#mega_files').click(function() { 
    $morenum = 0; 
     $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
     $("#contentjq").load("http://site.com/files.php?more=" + $morenum + "&movies=1"); 
     $("#contentjq_more").empty().html(''); 
    $morenum = $morenum+20; 
     $("#contentjq").show(); 
}); 

$('#mega_music').click(function() { 
    $morenum = 0; 
     $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
     $("#contentjq").load("http://site.com/music.php?more=" + $morenum + "&movies=1"); 
     $("#contentjq_more").empty().html(''); 
    $morenum = $morenum+20; 
     $("#contentjq").show(); 
}); 
+2

嘛,你嘗試過什麼?這裏沒有「問題」,只有一個「任務」。如果嘗試了*,可能會出現問題,然後會發生某些意外事件。爲了讓其他人查看您的代碼並提供建議,請嘗試使用代碼審查網站。 – 2012-12-13 22:57:10

+3

http://codereview.stackexchange.com是你要找的 –

回答

1

您可以:

function DoClick(page) 
{ 
    $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
    $("#contentjq").load("http://site.com/" + page + ".php?more=" + $morenum + "&movies=1"); 
    $("#contentjq_more").empty().html(''); 
    $morenum = $morenum+20; 
    $("#contentjq").show(); 
} 

$('#mega_online, #mega_online, #mega_music').click(function() { 
    DoClick($(this).attr('id').split('_')[1]); 
}); 
2

我看到他們幾乎是相同的,你可以簡單地把他們趕出一個函數,找到網頁名稱爲pageName = this.id.split('_')[1]

function myFunc() { 
     var pageName = this.id.split('_')[1]; 
     $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
     $("#contentjq").load("http://site.com/" + pageName + "?more=" + $morenum + "&movies=1"); 
     $("#contentjq_more").empty().html(''); 
    $morenum = $morenum+20; 
     $("#contentjq").show(); 

} 

,然後你可以

$('#mega_online, #mega_files, #mega_music').click(function() { 
    myFunc.call(this); 
}); 
0

你可以把它變成一個功能:

function doWork($type) { 
     $morenum = 0; 
     $("#contentjq_more").empty().html('<center><img src="http://site.com/image.gif" /></center>'); 
     $("#contentjq").load("http://site.com/" + $type + ".php?more=" + $morenum + "&movies=1"); 
     $("#contentjq_more").empty().html(''); 
     $morenum = $morenum+20; 
     $("#contentjq").show(); 
     } 

$('#mega_music').click(function() { 
doWork('music'); 
}); 

$('#mega_files').click(function() { 
doWork('files'); 
}); 

$('#mega_online').click(function() { 
doWork('online'); 
}); 
+0

你不必綁定到每個元素。你可以在一個聲明中做到這一點。 – webnoob

+0

是的,但對新手來說不那麼容易混淆。 – bobthyasian

+0

不,它不是。理解逗號分隔列表並不難。 – webnoob