当我单击对话框的“确定”按钮时,出现“ referenceError:警报未定义”。当我从同一文件调用“渲染”功能时,代码按预期工作正常。当我导出“警报”并从另一个文件调用“渲染”功能时,出现参考错误问题。我希望它可重用,但在其他文件中调用它。我需要一些帮助。这是我的代码段。
//dialogs.js
function CustomAlert(){
this.render = function(dialog){
let winW = window.innerWidth;
let winH = window.innerHeight;
let dialogoverlay = document.getElementById('dialogoverlay');
let dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = 'block';
dialogoverlay.style.height = winH+'px';
dialogbox.style.left = (winW/2) - (550 * .5)+'px';
dialogbox.style.top = '100px';
dialogbox.style.display = 'block';
document.getElementById('dialogboxhead').innerHTML = 'Acknowledge this message';
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
};
this.ok = function(){
document.getElementById('dialogbox').style.display = 'none';
document.getElementById('dialogoverlay').style.display = 'none';
};
}
export let Alert = new CustomAlert();
//user.js
import {Alert} from './dialogs.js';
.
.
.
.catch(error => {
console.log('Failure', error);
Alert.render('Something wrong happened, Please try again.');
});
//signup.html
<script src="js/dialogs.js" type="module"></script>
<script src="js/user.js" type="module"></script>
答案 0 :(得分:1)
Inline event handlers在全局范围中进行评估。由于您正在使用模块,因此模块中定义的每个变量都是模块作用域的。最简单的解决方案是创建一个全局Alert
变量:
export let Alert = new CustomAlert();
window.Alert = Alert;
正确的解决方案是不使用HTML和内联事件处理程序,而是通过DOM方法和bind a proper function创建按钮,该按钮关闭模块范围并可以访问Alert
:
const button = document.createElement('button');
button.addEventListener('click', () => Alert.ok());
document.getElementById('dialogboxfoot').appendChild(button);