使用Js完成一个简单事件响应。向姓名文本框中输入你的姓名,点击“欢迎语”按钮,在文本区中显示如图所示内容,其中的姓名和日期是通过获取得 来,然后点击“获取日 期”按钮,能够获取到文本区中“今天是〞后面的日期内容,将此内容弹出对话框形式显示。1. 创建两个运算函数 2. 获取文本输入框的值 3,通过单击“欢迎语〞按钮调用创建的西数,将结果显示在文本区中 4. 通过“获取日期”按钮来调用创建的函数得到结果显示在弹出的对话 框内。
时间: 2023-11-22 13:54:49 浏览: 37
以下是一个简单的实现:
HTML代码:
```
<input type="text" id="nameInput">
<button id="welcomeBtn">欢迎语</button>
<button id="dateBtn">获取日期</button>
<br><br>
<textarea id="output" cols="30" rows="10"></textarea>
```
JS代码:
```
// 1. 创建两个运算函数
function getWelcomeMsg(name) {
return `你好,${name}!今天是${getCurrentDate()}。`;
}
function getCurrentDate() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}年${month}月${day}日`;
}
// 2. 获取文本输入框的值
const nameInput = document.getElementById('nameInput');
const welcomeBtn = document.getElementById('welcomeBtn');
const dateBtn = document.getElementById('dateBtn');
const output = document.getElementById('output');
// 3. 通过单击“欢迎语”按钮调用创建的函数,将结果显示在文本区中
welcomeBtn.addEventListener('click', () => {
const name = nameInput.value;
const msg = getWelcomeMsg(name);
output.value = msg;
});
// 4. 通过“获取日期”按钮来调用创建的函数得到结果显示在弹出的对话框内。
dateBtn.addEventListener('click', () => {
const date = getCurrentDate();
alert(`今天是${date}`);
});
```
运行代码后,输入姓名,点击“欢迎语”按钮即可在文本区中看到欢迎语和当前日期。点击“获取日期”按钮,将会弹出一个对话框显示当前日期。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)