javascript - 获取变量值并将它们放在另一个文件中
问题描述
我正在对游戏进行分块编码,我有一个名为 lineCount 的变量,它计算换行符的数量。但是,此变量位于名为 lib-dialog.js 的文件中。当我用 innerHTML 插入这个变量的值时,我可以通过在 soy.js 文件中创建一个 div 来获取行的值(我需要处理结果的文件)但是我需要这个值在一个变量中来放置一个 if (行 == 6){ }
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
document.getElementById("contarBloco").innerHTML = lineCount;
var contandoBloco = lineCount;
}
我需要获取变量 lineCount 并将其值放在另一个 js 中。但我只是设法将它插入到带有 innerHTML 的 div 中
解决方案
最好使用 localstorage 。在本地存储中设置localcount的值,去你想去的地方
var lineCount = noComments.split('\n').length;
localStorage.setItem("lineCount", lineCount); // in first file
var count = localStorage.getItem("lineCount") // in second file
使用此逻辑,您将获得值,但它将是字符串,然后您可以直接使用字符串或使用 parseInt 方法转换为整数
parseInt(count);
可能会有所帮助。谢谢