对于onclick事件,每一次的e.target所获得的对象取决于onclick的地方。与变量不同。
实例代码:
<html><body><div id="region-radio-wrapper"></div><div id="product-radio-wrapper"></div><div id="table-wrapper"></div><script>var checkboxDiv1 = document.querySelector("#region-radio-wrapper");var checkboxDiv2 = document.querySelector("#product-radio-wrapper");var checkboxOption1 = [{
value: 1,text: "华东",},{
value: 2,text: "华北",},{
value: 3,text: "华南",},];var checkboxOption2 = [{
value: 1,text: "手机",},{
value: 2,text: "笔记本",},{
value: 3,text: "智能音箱",},];function generate(checkboxDiv, checkboxOption) {
var span1 = document.createElement("span");checkboxDiv.appendChild(span1);var inputAll = document.createElement("input");span1.textContent = "全选:";span1.appendChild(inputAll);inputAll.setAttribute("checkbox-type", "all");inputAll.type = "checkbox";for (i = 0; i < checkboxOption.length; i++) {
var span = document.createElement("span");checkboxDiv.appendChild(span);var input = document.createElement("input");span.textContent = " " + checkboxOption[i]["text"] + ":";span.appendChild(input);input.setAttribute("checkbox-type", "one");input.type = "checkbox";}checkboxDiv.onclick = function (e) {
var source = e.target;if (source.type == "checkbox") {
var customA = source.getAttribute("checkbox-type");var input2 = source.parentNode.parentNode.querySelector("span:nth-of-type(2)").querySelector("input");var input3 = source.parentNode.parentNode.querySelector("span:nth-of-type(3)").querySelector("input");var input4 = source.parentNode.parentNode.querySelector("span:nth-of-type(4)").querySelector("input");if (customA == "all") {
if (source.checked == true) {
if (//有一个不是trueinput2.checked != true ||input3.checked != true ||input4.checked != true) {
source.checked = true;input2.checked = true;input3.checked = true;input4.checked = true;}} else {
e.preventDefault();}} else {
if (//全是trueinput2.checked == true &&input3.checked == true &&input4.checked == true) {
inputAll.checked = true;}if (inputAll.checked == true) {
if (input2.checked != true ||input3.checked != true ||input4.checked != true) {
inputAll.checked = false;//我曾经把这里写错了写成了source.checked}}}}};}generate(checkboxDiv1, checkboxOption1);generate(checkboxDiv2, checkboxOption2);</script></body>
</html>