gpt4 book ai didi

javascript - 使提示框创建警报

转载 作者:行者123 更新时间:2023-11-29 15:26:40 24 4
gpt4 key购买 nike

我正在尝试使用 Javascript 创建表单。

我需要在表单中填写姓名和年龄。输入字段后,请单击“提交”。提交需要创建一个提示,让您输入新的背景颜色。

单击“确定”后,我需要一个提示,上面写着(字段名称中的名称“您最喜欢的颜色已应用于页面背景”“您的年龄是(显示年龄字段中的年龄)

示例:Brad 您最喜欢的颜色已应用于页面背景。你的年龄是 33 岁。我不知道如何让 javascript 获取在姓名和年龄字段中输入的姓名和年龄。

HTML代码:

    <form>
First name:<br>
<input type="text" name="firstname" id="name"><br>
Age:<br>
<input type="text" name="txtage" id="age"><br>
<input type="submit" name="submit" id="process" onclick="MyFunction">
</form>

外部 Java 脚本:

function MyFunction() {
x = prompt("Enter the color you want on the Background???");
document.body.style.backgroundColor = x;
if (x != null){
alert("(need name from form)Your favorite color was applied to the background of the page, your age is (need age from form) ");
}
}

最佳答案

获取 <input> 的一种方法来自 DOM 的元素是将其 id 与 document.getElementById 一起使用.从这个 <input> 抓取输入文本的方法来自它的.value属性(property)。

因此,要从 ID 为 name 的输入中获取字符串文本, 你会做

var name = document.getElementById("name").value;

这可能是这样的:

function MyFunction() {
x = prompt("Enter the color you want on the Background???");
document.body.style.backgroundColor = x;

var name = document.getElementById("name").value;
var age = // ...get the age in a similar manner

if (x != null) {
// concat strings using the + operator
alert(name + "Your favorite color was applied to the background of the page, your age is " + age);
}
}

关于javascript - 使提示框创建警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com