script.js怎么写
时间: 2024-04-27 15:25:36 浏览: 12
script.js 是一个 JavaScript 文件,可以在 HTML 文件中使用 <script> 标签引用。在 script.js 文件中,你可以编写 JavaScript 代码来操作 HTML 页面、处理用户输入、发送网络请求等等。以下是一个简单的 script.js 文件示例:
``` javascript
// 获取 HTML 元素
const button = document.querySelector('button');
const input = document.querySelector('input');
const div = document.querySelector('div');
// 给按钮绑定点击事件
button.addEventListener('click', () => {
const value = input.value;
// 发送网络请求
fetch(`https://api.example.com?q=${value}`)
.then(response => response.json())
.then(data => {
// 处理返回数据
div.textContent = data.results[0].text;
})
.catch(error => {
// 处理错误
console.error(error);
});
});
```
上面的代码演示了如何在按钮点击时,获取输入框的值,发送网络请求,处理返回数据,并将结果显示在页面上。当然,实际的应用场景会更加复杂。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)