从数组添加按钮的值

问题描述 投票:1回答:5

编辑:我想插入value =“questions [questionNum] ['choices'] [i]”,我不知道这样做的语法。

我希望使用多级数组中的值来更改按钮的值。它适用于单选按钮,但这次我想使用标准按钮。

$('#showChoices').append('<input type="button" id="buttons">' +  questions[questionNum]['choices'][i] + '</input>');

这有效,但以下情况并非如此:

$('#showChoices').append('<input type="button" id="buttons" value='"questions[questionNum]['choices'][i]"'></input>');

JSBin of the first

谢谢

javascript jquery html
5个回答
4
投票

你只是想用JavaScript设置value道具?您只需要在值之后使用字符串连接添加值,就像在第一个示例中一样。

$('#showChoices').append('<input type="button" id="buttons" value=' +  questions[questionNum]['choices'][i] + '></input>');

或者,如果你想要你可以尝试template strings

$('#showChoices').append(`<input type="button" id="buttons" value=${questions[questionNum]['choices'][i]}></input>`);

他们使用反引号而不是单引号或双引号而不是连接(使用+'s)你只是直接在字符串中编写JavaScript,有点像你的例子 - 但它需要包装在${}


1
投票

试试这个 :

$('#showChoices').append('<input type="button" id="buttons" value="'+ questions[questionNum]['choices'][i] +'"/>');

1
投票

您需要使用字符串连接来添加值。此外,id必须是唯一的,所以我在你的id中添加了选择索引,使它们成为唯一。

var questions = {'questionNum' : {'choices' : ['foo', 'bar'] }};
for(var i = 0; i < questions.questionNum.choices.length; ++i) {
  $('#showChoices').append('<input type="button" id="buttons'+[i]+'" value="' + questions.questionNum.choices[i] +'"></input>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='showChoices'></div>

1
投票

这就是你需要的

$('#showChoices').append('<input type="button" id="buttons" name="buttons" value='+butVal+'></input>');

1
投票

你知道,在回答这个问题后,我不禁觉得我们都有隧道视野。也许这并不重要,但我觉得如果你使用jQuery,你应该首先使用attr()方法而不是字符串连接。所以:

$('<input type="button" id="buttons">').attr('value', questions[questionNum]['choices'][i]).appendTo('#showChoices');

实际上我可能会写。 (我将append更改为appendTo`以允许我链接两个属性,只允许一行。


我还注意到:输入元素不应该被关闭 - 它是一个“自闭”标记,这意味着你不要在最后添加一个</input>

正如你在别处问过的那样:是的,为了实现可行性,我会将所有代码保存到变量中。所以:

const choice = questions[questionNum]['choices'][i]; // maybe even break this down into several variables. It's quite deep
$('<input type="button" id="buttons">').attr('value', choice).appendTo('#showChoices');
© www.soinside.com 2019 - 2024. All rights reserved.