javascript - 如何在头部的脚本标签中传递参数
问题描述
我有一个 html 页面index.html
。在该head tag
页面中,我想定义一个脚本 src:
<script src="http://www.example/hrm.js?pId=5"></script>
我希望 pId 编号由我提供给我的 html 文件的参数填写。例如,如果我打开.../index.html?pId=6
,我想在该页面的脚本标签中
<script src="http://www.example/hrm.js?pId=6"></script>
我怎样才能做到这一点?我试过这个:使用 JS 变量设置 <script> 标签的 src 属性, 但问题是我有多个脚本要加载!当我输入那段代码时,什么都没有了。
解决方案
你可以使用这个:
var pId = new URL(document.currentScript.getAttribute('src')).searchParams.get("pId");
参考:
注意:根据 MDN URL IE 不支持,查看链接查看支持的浏览器,可能有 polyfill。IE 也不支持currentScript 。
推荐阅读
- excel - VBA - Ranking Highest to Lowest by Counting Negative Values?
- intellij-idea - Intellij Idea 在每一行中插入空格并显示整个文件在 git pull 请求中被修改
- c - Can't understand &(sizeof 2[a])[a]
- c# - 在 WPF (C#) 中将 RAW 图像加载到 Canvas
- sublimetext3 - Exclude unpacked packages from Package Control menu
- amazon-s3 - Stream 'Azure Blob Storage' file URL to Amazon S3 bucket
- database - 如何在 phpmyadmin 中将我的 id 计数器重置为 1?
- python-3.x - Keras LSTM 和嵌入连接数组维度问题
- python - 烧瓶表格未发布
- mysql - 如何从左连接返回所有空值?