js src 传参
时间: 2023-07-12 22:20:01 浏览: 162
要在 JavaScript 中向一个脚本文件传递参数,可以使用以下方法:
1. 在 HTML 中使用 script 标签时,使用 data-* 属性传递参数:
```html
<script src="script.js" data-param1="value1" data-param2="value2"></script>
```
在 script.js 文件中,可以使用以下方式获取参数:
```javascript
const param1 = document.currentScript.getAttribute('data-param1');
const param2 = document.currentScript.getAttribute('data-param2');
```
2. 在 JavaScript 中使用 XMLHttpRequest 对象加载脚本文件时,可以在 URL 中添加参数:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('GET', 'script.js?param1=value1¶m2=value2', true);
xhr.onload = function() {
// 脚本加载完成后的处理逻辑
};
xhr.send();
```
在 script.js 文件中,可以使用以下方式获取参数:
```javascript
const urlParams = new URLSearchParams(window.location.search);
const param1 = urlParams.get('param1');
const param2 = urlParams.get('param2');
```
注意,第二种方法需要服务器支持 CORS,否则会因为跨域问题而无法加载脚本文件。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)