首页 > 解决方案 > 如何在头部的脚本标签中传递参数

问题描述

我有一个 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 属性, 但问题是我有多个脚本要加载!当我输入那段代码时,什么都没有了。

标签: javascripthtml

解决方案


你可以使用这个:

var pId = new URL(document.currentScript.getAttribute('src')).searchParams.get("pId");

参考:

注意:根据 MDN URL IE 不支持,查看链接查看支持的浏览器,可能有 polyfill。IE 也不支持currentScript 。


推荐阅读