如何将变量从HTML传递到Javascript进行调试和发布



我正在通过VSCode和live-server构建和调试应用程序,并且我将应用程序托管在本地XAMPP apache服务器上。

我想保持javascript代码相同,只是在live-server和apache之间切换

我认为这样做的方法是通过在VSCode中为apache保留index.html和为live-server保留debug.html

那么在index。html中我要这样写:

<body>
<div id="main_div" style="position: relative; "></div>
<script type="text/javascript" src="main.js">
bbCSV = 'http://xxx.xxx.xxx.xxx/BB.csv';
smtCSV = 'http://xxx.xxx.xxx.xxx/SMT.csv';
</script>    
</body>

其中xxx.xxx.xxx.xxx为服务器IP

在debug。html中我将写入这个

<body>
<div id="main_div" style="position: relative; "></div>
<script type="text/javascript" src="main.js">
bbCSV = 'http://localhost:8080/BB.csv';
smtCSV = 'http://localhost:8080/SMT.csv';
</script>    
</body>

但是这些变量在javascript文件中不起作用,大概是因为它们是在解析main.js之后创建的。

有没有办法在JavaScript文件加载之前创建变量?

或者有更好的方法来做这件事?

当您使用带有src的脚本标记时,其中的所有脚本将被加载的脚本覆盖。

试试这个:

<body>
<div id="main_div" style="position: relative"></div>
<script type="text/javascript">
bbCSV = "http://localhost:8080/BB.csv";
smtCSV = "http://localhost:8080/SMT.csv";
</script>
<script type="text/javascript" src="main.js"></script>
</body>

使用chrome扩展启动调试器会话,或者您可以在代码中键入' debugger '并打开调试器工具来暂停脚本

vscode Chrome Debugger

同样,先加载变量,然后加载JS文件。事情是同步运行的,所以你的文件在加载时不会看到这些。


<script type="text/javascript">
const bbCSV = 'http://localhost:8080/BB.csv';
const smtCSV = 'http://localhost:8080/SMT.csv';
</script>
<script type="text/javascript" src="main.js"></script>    

最新更新