如何在外部js文件中传递和获取值

huangapple go评论53阅读模式
英文:

How to pass and get value with external js file

问题

可以像这样传递一个值给一个 js 文件吗,如果不行,怎么做?

是的,你注意到我有一个参数 280,我想在我的 create.js 中使用它。

我该如何将一个斜杠参数传递给 js 文件本身?

英文:

Can I pass a value to a js file like this, if not, how ?

<script type="text/javascript" src="create.js/280"></script>

Yes, you notice that I have a parameter 280 which I want to use in my create.js

how could I pass a slash parameter to the js file itself ?

答案1

得分: 2

document.currentScript 会提供对当前正在运行的 <script> 元素的访问。

然后,您可以使用 getAttribute 方法 来读取 src 并按您喜欢的方式进行解析(例如,使用 正则表达式)来从 URL 的其余部分分离出 280

我建议将 280 移动到 data-* 属性,然后使用 document.currentScript.dataset.yourDataName 进行读取。除了更简单外,这将允许脚本在数字更改时仍然可以被缓存。

<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->

<!-- 语言: lang-html -->
  <script data-your-data-name="280">
    console.log(document.currentScript.dataset.yourDataName);
  </script>
<!-- 结束代码片段 -->
英文:

document.currentScript will give you access to the currently running &lt;script&gt; element.

You can then use the getAttribute method to read the src and parse it however you like (e.g. a regular expression) to split the 280 from the rest of the URL.

I'd recommend moving the 280 to a data-* attribute and then reading it with document.currentScript.dataset.yourDataName. Aside from being simply easier, it will allow the script to be cached even if the number changes.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;script data-your-data-name=&quot;280&quot;&gt;
  console.log(document.currentScript.dataset.yourDataName);
&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月24日 00:24:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定