Javascript 将java脚本数组元素作为输入字段值输入html表单?
我有6个引导卡,其中卡的详细信息是id、内容。单击每一张卡,我将从本地存储中获取单击卡的ID到数组中,现在我想将该ID作为输入字段的值发送到html表单 我的html代码是:Javascript 将java脚本数组元素作为输入字段值输入html表单?,javascript,html,arrays,Javascript,Html,Arrays,我有6个引导卡,其中卡的详细信息是id、内容。单击每一张卡,我将从本地存储中获取单击卡的ID到数组中,现在我想将该ID作为输入字段的值发送到html表单 我的html代码是: <body onload = "sample(),issample()"> <div class="form-group" > <input type="text" name="goal" id="goal" value=" "> </div> <div clas
<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">
我得到的错误是未定义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);
}
您在
getGoal
函数中声明了goalIds
,并且它仅在函数中可用,除非您将数组放置在其他位置(如窗口
范围)@Thum那么现在我如何在另一个函数中访问goalids呢?你能告诉我代码吗?@Thum当我编写你的代码时,当我点击卡片时,重复的ID进入数组。你可以在getGoal
中将goalids
重置为[]
。@Thum你能举个例子吗?更新了答案
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);
}