2012-03-16 49 views
2

我有兩個html文件(用於添加和編輯),其中包含js代碼。這兩個文件是相同的,除了其功能中的幾條js線。其實我不喜歡兩個文件都有共同的代碼。有沒有一種處理這種情況的好方法?如何保持兩個js文件的一致性?

例子:

(文件一)

<html> 
    <title>title goes here</title> 
     <javascript> 

      $('#button1').click(function() { 
      $.ajax({ 
       type: "POST",  
       url: '/admin/test/checkcode', 
       data: {code:code, id:id}, // in here there is an id 
       async: false,      
       success: function(data){ 
       } 
      }); 
      } 
     </script> 
    <body> 

    </body> 
</html> 

(文件二)

<html> 
    <title>title goes here</title> 
     <javascript> 

      $('#button1').click(function() { 
      $.ajax({ 
       type: "POST",  
       url: '/admin/test/checkcode', 
       data: {code:code}, // in here there is no id 
       async: false,      
       success: function(data){ 
       } 
      }); 
      } 
     </script> 
    <body> 

    </body> 
</html> 

回答

2

你可能想嘗試把該JavaScript代碼到一個單獨的文件。這樣,您可以將單個JavaScript文件包含到每個頁面中,只需對該JavaScript文件進行更改即可。

供參考,在這裏是一種方法,包括JavaScript文件:

<script type="text/javascript" src="javascript_file_here.js"></script> 

內部的JavaScript文件中,可能會有一些類型的基本功能,這需要參數是在使用的data值致電$.ajax()。例如,像:

function example(data1, data2) { 
    // your code here 
    // then just check for data1 and data2 (etc.) 
    // to see what to include in the `data:` 
} 
+1

感謝summea的答覆。根據你的答案,我將不得不再次寫兩次相同的Ajax函數,只是因爲它的一行改變了? – Rohitha 2012-03-16 04:17:46

+0

@Rohitha我明白你的意思了;在這種情況下,您可能還想在JavaScript文件中創建某種函數參數...以讓代碼知道爲什麼要包含「data:」值。 – summea 2012-03-16 04:20:41

+0

@Rohitha更新我的回答,擴大一點評論... – summea 2012-03-16 04:23:45

相關問題