选中三个复选框后,如何使附加的脚本立即将用户重定向到生成的页面?
const inputs = document.querySelectorAll('input');
const obj = {
a: {
path: '',
isChecked: false
},
b: {
path: '',
isChecked: false
},
c: {
path: '',
isChecked: false
},
}
inputs.forEach(addListener);
function addListener(input) {
input.addEventListener('click', onClickHandler);
}
function onClickHandler(e) {
changeObjectValues(obj[e.target.name], e.target.value, true);
const checkedInputs = getСlosestCheckedInputs(e.target);
if (checkedInputs.length > 0) uncheckInputs(checkedInputs);
if (isAllChecked()) {
const url = 'https://site.ru' + Object.keys(obj).map(getPath).join('');
alert(url);
}
}
function getPath(key) {
return obj[key].path;
}
function isAllChecked() {
return Object.keys(obj).every(isChecked);
}
function isChecked(key) {
return obj[key].isChecked === true;
}
function changeObjectValues(obj, path, isChecked) {
obj.path = path;
obj.isChecked = isChecked;
}
function getСlosestCheckedInputs(target) {
const inputs = target.parentNode.parentNode.querySelectorAll('input[type="checkbox"]');
const checkedInputs = [];
inputs.forEach(function getCheckedInput(input) {
if (input.checked && input != target) checkedInputs.push(input);
});
return checkedInputs;
}
function uncheckInputs(checkedInputs) {
checkedInputs.forEach(function uncheck(input) {
input.checked = false;
})
}
.container {
display: flex;
flex-direction: column;
margin-bottom: 1rem;
}
.a>.row {
background-color: lightgreen;
}
.b>.row {
background-color: lightblue;
}
.c>.row {
background-color: wheat;
}
<!-- A -->
<div class="a container">
<div class="row">
<input id="a-1" type="checkbox" value="/a-1/" name="a">
<label for="a-1">a 1</label>
</div>
<div class="row">
<input id="a-2" type="checkbox" value="/a-2/" name="a">
<label for="a-2">a 2</label>
</div>
</div>
<!-- B -->
<div class="b container">
<div class="row">
<input id="b-1" type="radio" value="b-1/" name="b">
<label for="b-1">b 1</label>
</div>
<div class="row">
<input id="b-2" type="radio" value="b-2/" name="b">
<label for="b-2">b 2</label>
</div>
</div>
<!-- C -->
<div class="c container">
<div class="row">
<input id="c-1" type="checkbox" value="c-1" name="c">
<label for="c-1">c 1</label>
</div>
<div class="row">
<input id="c-2" type="checkbox" value="c-2" name="c">
<label for="c-2">c 2</label>
</div>
</div>
1 个回答