Javascript 在单个HTML中具有相同名称的两个JS函数

Javascript 在单个HTML中具有相同名称的两个JS函数,javascript,jquery,html,Javascript,Jquery,Html,我有一个功能。其中,数据从getValue()函数获取值 下面的代码是一个片段 grid.js function gridLoadComplete(){ var data = getValue(); } 考虑一下下面的HTML html-包含以下两个片段 staffGrid.html studentGrid.html 我已经将grid.js片段添加到staffGrid.html&teacherGrid.html。 当我加载index.html时,它会得到一个错误。我

我有一个功能。其中,
数据
从getValue()函数获取值

下面的代码是一个片段

grid.js

function gridLoadComplete(){
    var data = getValue();      
}
考虑一下下面的HTML

  • html-包含以下两个片段
    • staffGrid.html
    • studentGrid.html
我已经将
grid.js
片段添加到staffGrid.html&teacherGrid.html。

当我加载index.html时,它会得到一个错误。我在
数据中没有得到值,因为它被调用了两次

有没有办法解决这个问题。使用相同的函数名
getvalue()



你应该考虑对你的JavaScript进行命名空间,这样每个片段都有自己的命名空间。例如:

staffGrid.html
将包含:

<script>
var staffGrid = {
    gridLoadComplete: function() {
        var data = getValue();
    },

    myOtherFunc: function() {
        //Do other stuff...
    }
};
</script>

var staffGrid={
gridLoadComplete:函数(){
var data=getValue();
},
myOtherFunc:function(){
//做其他事情。。。
}
};

然后在
index.html
中,可以调用:
staffGrid.gridLoadComplete()
teacherGrid.gridLoadComplete()

看起来您的问题是因为您的全局代码太多,并且您的代码不是模块化的

一种解决方案是编写
grid.js
文件的方式是公开可以实例化并封装其逻辑的
grid
组件,这样
index.html
页面就可以创建独立的
grid
组件实例

您可以将网格或任何UI组件视为可重用的组件,例如本机
元素

在同一页面中使用2个select元素可以做什么

index.html

$(function () {
    var $select1 = $('#select-1'), //this could be staffGrid = new Grid('#staff-grid')
        $select2 = $('#select-2');

    //Make a parallel with the change event and your gridLoadComplete event.
    //gridLoadComplete should be fired by your grid component itself and your component
    //should allow to listen to those events.

    //It could be staffGrid.on('loadComplete', function () { staffGrid.getValue(); });
    $select1.change(function () {
        $select1.val(); //access select1 value
    });

    $select2.change(function () {
        $select2.val(); //access select2 value
    });
});

正如您在上面的示例中所看到的,我们调用相同的
val
函数来获取值,但是针对不同的实例,这允许我们在不复制
val
函数逻辑的情况下获取所需的值。

因此,您尝试从index.html调用
grindLoadComplete()
,但是把它grid.js链接到staffGrid.html和teacherGrid.html,对吗?尝试将grid.js链接到index.html。这是三个独立的文件,它们不会共享源代码,除非您让第四个文件调用它,它将这三个文件结合在一起(不带框架,这不起作用)。我无法将
grid.js
链接到index.html。Bcoz getValue()函数在staffgrid&studentgrid.htmlh中返回不同的值。您是如何将它们作为片段包含的?它们返回不同的值这一事实应该会对包含它产生任何影响。您所描述的是,您有三个独立的文件,其中两个链接到grid.js文件,而第三个是您需要从中调用的文件。现在您可以说,它在staffGrid.html中显示的信息与studentGrid.html中显示的信息不同,这表明您需要从staffGrid.html调用它,而不是从index.html调用它。也许您可以解释这三个文件是如何连接的,这样我们就可以理解为什么需要从index.html而不是staffGrid.html和strudentGrid.html调用函数。@coderboi_89这是我的错误。我已经更正了问题..这并不能解决
getValue
问题。如果将
getValue
添加到您的对象文本中,那么您将在网格文件中复制逻辑。谢谢。!模块化方法可以解决我的问题。。很好的一天。。!