用Javascript在一行中创建复选框



我试图建立一个简单的网页,动态创建一行复选框。首先,我想出了如何将复选框放在一行中:

.checkbox-inline {
display: inline-block;
}
<form role="form" method="post">
<legend>What is Your Favorite Pet?</legend>
<label class="checkbox-inline">
<input type="checkbox" name="cbpets[]" value="Cats">
Cats
<br>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="cbpets[]" value="Dogs">
Dogs
<br>
</label>
</form>

接下来,我发现这个页面StackOverflow问题(见第一个答案),并能够创建复选框,但跨多行。现在我被困住了。我试图把复选框在一行,但没有想到如何。我试着添加(使用stackoverflow答案中的语法)

var color = document.createElement("input");   
color.setAttribute(
'style',
'class="checkbox-inline"',
);

但这不起作用。你还有什么建议我试试的吗?

您不需要使用display: inline-block;强制所有复选框在线。只需删除label中的<br>标签,然后所有复选框将显示在一行中。

<form role="form" method="post">
<legend>What is Your Favorite Pet?</legend>
<label class="checkbox-inline"><input type="checkbox" name="cbpets[]" value="Cats">Cats</label>
<label class="checkbox-inline"><input type="checkbox" name="cbpets[]" value="Dogs">Dogs</label>
</form>

您不需要为此做任何CSS样式,因为输入将默认为内联。

将您的宠物添加到数组中,遍历该数组并创建一些输入,然后将所有这些输入的结果添加到DOM中。

// Cache the container element
const container = document.querySelector('.container');
// Define the pets
const pets = ['Dog', 'Cat', 'Moose', 'Barbary macaque', 'Snail'];
// Temporary array to hold the input strings as
// we build them in the loop
const html = [];
// Loop over the pets array, create a new
// HTML string for each of them, and push that string
// into our temporary array
for (const pet of pets) {
const input = `
<label>
${pet}
<input type="checkbox">
</label>
`;
html.push(input);
}
// Add the completed HTML array to the container
// by `joining` all the elements into one string
container.insertAdjacentHTML('beforeend', html.join(''));
.legend { margin-right: 0.5em; font-weight: 700; }
<div class="container">
<span class="legend">What is Your Favorite Pet?</span>
</div>

附加文档

  • join

  • 模板/字符串文字
  • querySelector

最新更新