[英]How to use function of module in none module js file - Vanilla JS
[英]Is there any way to export JS variables within a module function to another file using vanilla JS?
我的 header.js 动态创建显示和隐藏我的页面的按钮。 这些页面各自在各自的 JS 文件中独立调制。 由于无法更改 function 上的 classList,如何导出必须更改 classList 的元素变量?
header.js
function header() {
const element = document.createElement('div');
element.innerHTML = `
<nav>
<button type="button" class="btn btn-dark" id="home"><a href="">Home</a></button>
<button type="button" class="btn btn-dark" id="menu"><a href="">Menu</a></button>
<button type="button" class="btn btn-dark" id="location"><a href="">Location</a></button>
</nav>
`;
// Add the image to our existing div.
const myIcon = new Image();
myIcon.src = Icon;
element.appendChild(myIcon);
return element;
}
document.body.appendChild(header());
export default header;
我的模块 mission.js 示例
const mission = () => {
const element = document.createElement('div');
element.classList.add('hide');
element.innerHTML = `
<div class='asl'>
<div class='mission' id='mission'>
<div class='text-content'>
<h2>Our Mission</h2>
<h4>Provide you with Handpicked, Artisanally Curated, Free Range, Sustainable, Organic Tea & Delicious Desserts</h4>
</div>
</div>
</div>
`;
return element;
};
document.body.appendChild(mission());
export default mission;
感谢你的帮助:)
您可以导出变量; 但是,您的常量是在 function 中声明的,并且常量是块范围的,因此在 function 括号之外无法访问它。
但是,您可以使用类似于模块模式的东西来导出变量:
const myModule = (function() {
const myVariable = 1;
function myFunction() {
return myVariable + 1;
}
function getmyVariable() {
return myVariable;
}
return {myFunction, getMyVariable};
}());
export { myModule };
然后你可以像这样使用它:
//import it
const variable = myModule.getMyVariable();
还有很多方法可以做到这一点,在 function 块之外声明常量,创建具有 getter 和 setter 的类或创建工厂函数。
ES 模块(即import
/ export
语法)是 Javascript 规范的一部分,也就是说,它们是“vanilla”。
然而,这并不意味着每个浏览器或其他 JS 运行时都支持它们,事实上有些仍然不支持,或者只是以某种临时方式支持。 MDN 的模块页面有一个图表,显示了对流行 JS 运行时的支持细分。
如果您的运行时不支持 ES 模块,它可能会支持旧的 CommonJS(即require
)语法。 如果两者都不支持,您将需要使用某种捆绑程序。
PS 另一件需要考虑的事情是时机。 当模块代码运行时,它会在加载时运行……但是 DOM 可能还没有准备好,这意味着使用document
的代码可能无法工作。 您必须将代码添加到某种DOMContentReady
或类似的事件处理程序,以确保首先加载模块,然后加载 DOM,然后运行该代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.