我有一个函数。其中 data
从 getValue() 函数获取值。
下面的代码是一个片段。
grid.js
function gridLoadComplete(){
var data = getValue();
}
考虑下面的 HTML
- Index.html - 包含以下两个片段
- staffGrid.html
- studentGrid.html
我已将 grid.js
片段添加到 staffGrid.html 和 teacherGrid.html。
当我加载index.html时,出现错误。我没有从 data
中获得值(value),因为它被调用了两次。
有什么办法可以解决这个问题吗?使用相同的函数名称 getvalue()
??
最佳答案
看来您的问题是由于您的全局变量太多并且您的代码不是模块化的这一事实而引起的。
一种解决方案是编写您的 grid.js
文件以公开 Grid
的方式可以实例化并封装其逻辑的组件,以便 index.html
页面可创建独立Grid
组件实例。
您可以将网格或任何 UI 组件视为可重用组件,例如 native <select>
元素。
在同一页面中使用 2 个选择元素可以做什么?
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
函数的逻辑。
关于javascript - 单个 HTML 中具有相同名称的两个 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059318/