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

时间:2014-09-26 12:13:50

标签: javascript jquery html html5

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

下面的代码是片段。

grid.js

function gridLoadComplete(){
    var data = getValue();      
}

考虑下面的HTML&#39>

  • Index.html - 包含以下两个片段
    • staffGrid.html
    • studentGrid.html

我已将grid.js片段添加到 staffGrid.html &的 teacherGrid.html。

当我加载 index.html 时,会出现错误。我没有在data获得价值,因为它被叫了两次。

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


2 个答案:

答案 0 :(得分:2)

看起来你的问题是因为你有太多的全局变量并且你的代码不是模块化的。

一种解决方案是以一种暴露grid.js组件的方式编写Grid文件,该组件可以实例化并封装它的逻辑,以便{ {1}}页面可以创建独立的index.html组件实例。

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

您可以在同一页面中使用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函数&# 39;逻辑。

答案 1 :(得分:0)

您应该考虑命名空间javascript,以便每个片段都有自己的命名空间。例如:

staffGrid.html将包含:

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

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

然后在index.html中,您可以致电:staffGrid.gridLoadComplete();teacherGrid.gridLoadComplete();