使用Js完成一个简单事件响应。向姓名文本框中输入你的姓名,点击“欢迎语”按钮,在文本区中显示如图所示内容,其中的姓名和日期是通过获取得 来,然后点击“获取日 期”按钮,能够获取到文本区中“今天是〞后面的日期内容,将此内容弹出对话框形式显示。1. 创建两个运算函数 2. 获取文本输入框的值 3,通过单击“欢迎语〞按钮调用创建的西数,将结果显示在文本区中 4. 通过“获取日期”按钮来调用创建的函数得到结果显示在弹出的对话 框内。
时间: 2023-11-22 10:54:29 浏览: 126
这里是一个简单的实现代码:
HTML:
```html
<label for="name">姓名:</label>
<input type="text" id="name" /><br /><br />
<button id="welcome-btn">欢迎语</button>
<button id="date-btn">获取日期</button>
<br /><br />
<textarea id="output" rows="5" cols="50"></textarea>
```
JavaScript:
```js
// 创建获取当前日期的函数
function getCurrentDate() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}年${month}月${day}日`;
}
// 创建欢迎语函数
function greet() {
const name = document.getElementById("name").value;
const currentDate = getCurrentDate();
const output = document.getElementById("output");
output.value = `欢迎你,${name}!今天是${currentDate}`;
}
// 绑定欢迎语按钮事件
document.getElementById("welcome-btn").addEventListener("click", greet);
// 绑定获取日期按钮事件
document.getElementById("date-btn").addEventListener("click", function() {
const currentDate = document.getElementById("output").value.split("今天是")[1];
alert(currentDate);
});
```
这段代码中,我们创建了两个函数:`getCurrentDate` 和 `greet`。`getCurrentDate` 函数用于获取当前日期,`greet` 函数用于生成欢迎语,并将其输出到文本区中。
然后我们绑定了两个按钮的点击事件,分别是“欢迎语”按钮和“获取日期”按钮。当点击“欢迎语”按钮时,会调用 `greet` 函数,生成欢迎语并输出到文本区中。当点击“获取日期”按钮时,会获取文本区中“今天是”后面的日期内容,并通过 `alert` 函数弹出对话框形式显示。
阅读全文
相关推荐


















