gpt4 book ai didi

javascript - 获取所有字段的数据

转载 作者:行者123 更新时间:2023-12-03 08:01:30 24 4
gpt4 key购买 nike

请帮我解决这个问题我想用随机数据填充所有字段 Improve this question

<html>
<head>
<script>
//<![CDATA[
window.onload=function(){
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");

var names = ["Henry", "Joseph", "Mark", "Michael"];

button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
}//]]>
</script>
</head>
<body>
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
<input type="text" id="my-input" />
<input type="text" id="my-input" />

</body>
</html>

最佳答案

我猜您的问题是您想要填充所有输入,但它没有这样做。

问题在于 id 是为唯一元素保留的。

因此,如果您将 id 的 HTML 更改为 class,则您会将 JavaScript 更改为如下所示:

var button = document.getElementById("my-button");
var inputs = document.getElementsByClassName("my-input");

var names = ["Henry", "Joseph", "Mark", "Michael"];

button.addEventListener("click", function() {
Array.prototype.forEach.call(inputs, function (input) {
input.value = names[Math.floor(Math.random() * names.length)];
});
});

关于javascript - 获取所有字段的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560998/

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