【问题标题】:How to keep consistency between two js files?如何保持两个js文件之间的一致性?
【发布时间】:2012-03-16 04:07:04
【问题描述】:

我有两个包含 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 jquery html ajax xhtml


    【解决方案1】:

    您可能想尝试将该 JavaScript 代码放入单独的文件中。这样一来,您就可以将单个 JavaScript 文件包含到每个页面中……并且只需对那个 JavaScript 文件进行更改。

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

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

    在该 JavaScript 文件中,可能存在某种类型的基本函数,该函数为 data 调用中使用的 data 值获取参数。例如,类似:

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

    【讨论】:

    • 感谢 summea 的回复。根据您的回答,我将不得不编写两次相同的 ajax 函数,因为它的一行被更改了?
    • @Rohitha 我明白你的意思;在这种情况下,您可能还想在您的 JavaScript 文件中创建某种函数参数...让代码知道为该 data: 值包含什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2014-02-21
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多