如何保持两个 js 文件之间的一致性

How to keep consistency between two js files?

本文关键字:文件 js 之间 一致性 两个 何保持      更新时间:2023-09-26

我有两个包含js代码的html文件(用于添加和编辑(。这两个文件是相同的,除了其功能中的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>

你可能想尝试将 JavaScript 代码放入一个单独的文件中。 这样,您只需将单个 JavaScript 文件包含在每个页面中......并且只需要对那一个 JavaScript 文件进行更改。

作为参考,这里有一种包含 JavaScript 文件的方法:

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

在该 JavaScript 文件中,可能有某种类型的基本函数,该函数为$.ajax()调用中使用的data值获取参数。 例如,类似这样的内容:

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