添加一个新复选框会使其他复选框处于未选中状态

Adding a new checkbox makes the other checkboxes unchecked

当我添加一个新的复选框时,旧的复选框被设置为未选中(即使它们已被选中)。我该如何解决?

这是我的代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function zaza() {
    document.body.innerHTML+=
        '<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>';
}

</script>
</head>
<body>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<p onclick="zaza()">add</p>
</body>
</html>

您正在添加具有相同名称的复选框,您必须为每个复选框指定不同的名称

问题是你覆盖了正文html:

document.body.innerHTML+=

改为尝试将复选框附加到正文。

function zaza() {
  var div = document.createElement('div');
  div.innerHTML = '<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>';
  document.body.appendChild(div);
}
p {
  cursor: pointer;
}
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<p onclick="zaza()">add</p>

您也可以去寻找文档片段:

function zaza() {
  var child = document.createDocumentFragment();
  var tmp = document.createElement('input');
  tmp.type = 'checkbox';
  tmp.name = 'vehicle';
  tmp.value = 'Bike';
  child.appendChild(tmp);
  child.appendChild(document.createTextNode('I have a bike'));
  child.appendChild(document.createElement('br'));
  document.body.appendChild(child);
}
p {
  cursor: pointer;
}
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<br>
<p onclick="zaza()">add</p>

您需要创建元素并追加到正文中

function zaza() {
    var answer = document.createElement('input');
    answer.setAttribute('type', 'checkbox');
    answer.setAttribute('id', 'answer');
    answer.setAttribute('value', 'a');
    var answerLabel = document.createElement('label');
    answerLabel.setAttribute('for', 'answer'); // this corresponds to the checkbox id
    answerLabel.appendChild(answer);
    answerLabel.appendChild(document.createTextNode(' I have a bike'));
    document.body.appendChild(answerLabel);
    linebreak = document.createElement("br");
    answerLabel.appendChild(linebreak);
}

DEMO