https://jsfiddle.net/urbandrone/y49df8wv/1/
另外,我在更改代码的地方添加了注释。基本上,你想做的是
不
包
<input>
元素
在…内
A.
<label>
,但是
在它旁边
并通过
id
<输入>
for
的属性
<标签>
. 这样,您可以只使用CSS更改标签的背景色,这几乎总是比使用JavaScript更好。
HTML格式
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="btn-group" data-toggle="buttons">
<span id=car></span>
</div>
</body>
</html>
.radio-toolbar input[type="radio"] {
display: none;
}
.radio-toolbar label {
display: inline-block;
background-color: #ddd;
padding: 4px 11px;
font-family: Arial;
font-size: 16px;
cursor: pointer;
}
.radio-toolbar .radio { /* style the wrapper */
position: relative; /* allows to "hide" the radio with absolute positioning (won't occupy space) */
display: inline-block; /* show wrappers in horizontal line */
}
.radio-toolbar input[type="radio"] { /* hide the <input> */
position: absolute;
z-index: -1;
}
.radio-toolbar input[type="radio"]:checked + label { /* target the <label> */
background-color: #000; /* changed to more obvious color */
}
JS公司
var array = ["Saab", "Volvo", "BMW"];
var item = document.createElement('div');
item.className = 'radio-toolbar';
for (var i = 0; i < array.length; i++) {
var wrapper = document.createElement('div'); // <-- create a wrapper element
var input = document.createElement('input');
var input_label = document.createElement('label');
input.type = 'radio';
input.name = 'radio-btn';
input.id = 'radio' + i;
input.checked = i === 0;
input.value = array[i]; // <-- <input>s should have different values
input_label.htmlFor = 'radio' + i; // <-- connect label to <radio> via for-attribute
input_label.innerHTML = array[i];
input_label.className = "btn btn-primary";
input_label.appendChild(input);
wrapper.className = 'radio'; // <-- add a class to the wrapper
wrapper.appendChild(input); // <-- add the <input>
wrapper.appendChild(input_label); // <-- add the <label>
item.appendChild(wrapper); // <-- add wrapper to toolbar
document.getElementById("car").appendChild(item);
}