我正在尝试将此功能导出到另一个文件。但是它不能正常工作。只是想确保我做对了所有事情?
window.colorAddElement = addedElements => {
const addedElementsDOMNode = document.getElementById(
`color-added-elements-"${num}"`,
)
if (colorAddNewClicked) {
text = " "
colorAddNewClicked = false
}
text += " " + addedElements
addedElementsDOMNode.innerHTML = text
}
导出:
module.exports.AddElement = window.colorAddElement = addedElements => {
const addedElementsDOMNode = document.getElementById(
`color-added-elements-"${num}"`,
)
if (colorAddNewClicked) {
text = " "
colorAddNewClicked = false
}
text += " " + addedElements
addedElementsDOMNode.innerHTML = text
}
导入:
const ColorAddElement = require("./colorSet.js")
通话:
ColorAddElement.AddElement(addedElements);
答案 0 :(得分:2)
假设您正在使用CommomJS
模块系统,则应执行以下操作:
ColorAddElement(addedElements);
通过导出,您仅在以下代码部分中导出函数:
module.exports.AddElement = window.colorAddElement = addedElements => {
const addedElementsDOMNode = document.getElementById(
`color-added-elements-"${num}"`,
)
if (colorAddNewClicked) {
text = " "
colorAddNewClicked = false
}
text += " " + addedElements
addedElementsDOMNode.innerHTML = text
}
因此,require函数的变量中存储的值就是您导出的函数:
const ColorAddElement = require("./colorSet.js"); // ColorAddElement is now your exported function