在script标签type="text/javascript"属性下导入方法变量
时间: 2023-12-04 12:02:38 浏览: 48
如果你想在 `script` 标签中导入方法和变量,可以使用全局变量的方式。具体来说,你可以在一个 JavaScript 文件中定义方法和变量,然后在另一个 JavaScript 文件中使用 `script` 标签引入该文件,并在该文件后面直接使用定义的方法和变量。示例代码如下:
```html
<!-- utils.js 文件 -->
<script type="text/javascript">
function add(a, b) {
return a + b;
}
const PI = 3.1415926;
</script>
```
```html
<!-- main.js 文件 -->
<script type="text/javascript" src="./utils.js"></script>
<script type="text/javascript">
console.log(add(1, 2)); // 输出 3
console.log(PI); // 输出 3.1415926
</script>
```
在上面的代码中,我们在 `utils.js` 文件中定义了 `add` 方法和 `PI` 变量,并使用 `script` 标签引入该文件。然后在 `main.js` 文件中,我们直接使用了 `add` 方法和 `PI` 变量,因为它们已经被定义在了全局作用域中。
需要注意的是,如果你在一个 JavaScript 文件中定义了多个方法和变量,这些方法和变量都会被定义在全局作用域中,可能会与其他方法和变量产生命名冲突。为了避免这种情况,建议使用模块化的方式来导入方法和变量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
<input type="button" value="新增" onclick="add()">
ID
姓名
年龄
密码
修改 删除
<c:if test="${not empty list }">
<c:forEach items="${list }" var="user" varStatus="s">
${s.count}
${user.username}
${user.age}
${user.password}
修改
删除
</c:forEach>
</c:if>
<script >function add(){
location.href="add.jsp";
}
function updatemethod(userid) {
var id = parseInt('<%= session.getAttribute("id") %>');
if (userid != id) {
alert("你不能修改别人的信息");
} else {
window.location.href = "update.jsp";
}
}
function deletemethod(userid) {
var id = parseInt('<%= session.getAttribute("id") %>');
if (userid != id) {
alert("你不能删除别人的信息");
} else {
if(confirm("你确定要删除自己的信息吗?")) {
window.location.href = "index.jsp";
}
}
}</script>
</body>
</html>上述代码哪里报错,要如何修改
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![chm](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)