gpt4 book ai didi

javascript - 将java脚本数组元素作为输入字段值放入html表单中?

转载 作者:行者123 更新时间:2023-12-02 22:15:19 25 4
gpt4 key购买 nike

我有 6 张引导卡,其中卡的详细信息是 id、内容。每张卡的 Onclick 我正在将单击的卡的 id 从本地存储获取到数组中,现在我想将该 id 发送到 html 表单作为输入字段的值我的html代码是:

<body onload = "sample(),issample()">

<div class="form-group" >
<input type="text" name="goal" id="goal" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">

我的JS代码是:

var goal = []
function getGoal(id, content) {
if (goal.length > 0) {
var data = { id: id, content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
var index = goal.indexOf(x)
if (index == -1) {
goal.push(x)
}
else {
goal.splice(index, 1)
}
}
else {
var data = { id: id, content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
goal.push(x)
}
localStorage.setItem("goal", JSON.stringify(goal))
// To get all ids
var storedNames = JSON.parse(localStorage.getItem("goal"))
var goalIds = []
if (storedNames)
storedNames.forEach(element => {
element = JSON.parse(element)
goalIds.push(element.id)
});
console.log(goalIds)
}
function issample(){
$("#goal").val(goalIds);
}

我收到错误,因为 goalIds 未定义,但 goalIds 数组正在获取 id,但 id 没有以值的形式获取

最佳答案

您已在 getGoal 函数中声明了 goalIds,并且只能在该函数中访问它。如果您需要在其他地方使用数组,那么您可以在函数外部声明它

var goal = [];
var goalIds = [];
function getGoal(id, content){
...code here

goalIds = [];

if (storedNames)
storedNames.forEach(element => {
element = JSON.parse(element)
goalIds.push(element.id)
});
console.log(goalIds)

// If you need to set the value for every `getGoal` call
issample();
}

function issample(){
$("#goal").val(goalIds);
}

关于javascript - 将java脚本数组元素作为输入字段值放入html表单中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59402882/

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