javascript - 弹出警报用户在文本框中写的内容
问题描述
我的大学有一个练习,我被困住了。我想创建一个页面,通过按“搜索”按钮将显示一个弹出窗口(警报),其中包含“学生 ID”的文本框内容,而按“插入”按钮将显示一个弹出窗口(警报),其中包含“名字”的文本框内容。
这是我的代码:
<html>
<body>
<form action="/action_page.php">
<label for="studentid">Student Id:</laber><br>
<input type="text" id="studentid" name="studentid"><br>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br><br>
<button type="button">Search</button>
<button type="button">Insert</button>
</form>
</body>
</html>
解决方案
编辑您的 HTML 以将其包含在按钮上:
<button type="button" onclick="search()">Search</button>
<button type="button" onclick="insert()">Insert</button>
并将其添加到末尾:
<script>
function search() {
let studentID = document.querySelector("#studentid").value;
alert(studentID);
}
function insert() {
let firstName = document.querySelector("#fname").value;
alert(firstName);
}
</script>
此 HTML 代码将在点击时分别运行 javascript 函数“ search()
”或“ insert()
”,它们执行以下操作:
- 创建一个变量,并将“
studentid
”或“fname
”元素的值分配给它。 - Alert() 变量的内容。
onclick
当单击它所在的元素时,该属性运行分配给它的 javascript。
推荐阅读
- javascript - Javascript 异步与 setTimeout(..., 0)
- c++ - 多个基类可以有相同的虚方法吗?
- c - 理解 C 中的 strcpy 和 char 数组
- java - 即使条件不满足,Java 是否完全了解整个递归方法?
- javascript - 为什么 moment.js 没有从 Node.js 中的 API 格式化日期?
- object - ThreeJS - 对象格式的网格线框
- python - 如何在返回/收益中停止额外的重复,同时仍然保持给定键的运行总数:值对?
- python - pandas 数据框在 matplotlibm 中绘制为表格,但缺少第一列
- c - 为什么要替换数组的第一个值?
- dart - Flutter - 如何通过布尔返回更改图标的颜色?