如何将变量传递给 .js 文件

how to pass variable into .js file

有什么方法可以将变量 "userID" 传递到导入的文件 "file.js?"

<script>

  var imported = document.createElement('script');
  var = userID;
  imported.src = 'https://website.com/file.js';
  document.head.appendChild(imported);

</script>

我不完全确定我理解你想要做什么,但也许全局变量是最直接的方法?

你可以

<script>

var imported = document.createElement('script');
// var = userID;
window.userID = 1234;
imported.src = 'https://website.com/file.js';
document.head.appendChild(imported);

</script>

然后在你导入的文件中你可以引用

window.userID // -> 1234
// or even just
userID // -> 1234 - though i would use the window.userID to at least be explicit

我想另一种更复杂的方法是 ajax js 文件的内容,并在将其附加到页面之前用 id 替换一些占位符。 顺便说一句,只有在您真正信任它的来源时,才像这样将 js 文件插入您的页面。

这会解决您的问题吗?