业务场景是什么样的呢?
就是我在选择单选框的时候,会弹出一个弹窗,询问你确定要更改选择吗?你点了确定,那就换了,点击取消,那就不变。
看看(我的)正常理解是怎么写的呢?
<input type="radio" name="sex" id="male">
<label for="male" onclick="select(this)">男</label>
<input type="radio" name="sex" id="female">
<label for="female" onclick="select(this)">女</label>
<script>
function select(o){
let id = o.getAttribute("for");
let preFor = id;
let bro = o.previousElementSibling;
if(confirm("确定要更改吗?")){
console.log("是的");
}else{
console.log("我后悔了");
bro.checked = false;
}
}
</script>
但是呢,上面代码有问题,根本无法实现取消选择的功能,这该怎么办呢?
解决办法:
先看代码:这个可是真折磨了我好久才想到的解决办法,如果你们有更好的解决办法,请评论告诉我。
效果
- 当你点击了现在被选中的那个单选框的
label
标签,不会有任何反应 - 当你点击了没被选中(即要更改选项了)的那个单选框的
label
标签,此时会弹出弹窗询问“确定要更改吗?”,点击确定,更改成功,对应单选框按钮被选中;点击取消,更改失败,不会有任何变化
<input type="radio" name="sex" id="male" checked="checked">
<label for="male" onclick="select(this)">男</label>
<input type="radio" name="sex" id="female">
<label for="female" onclick="select(this)">女</label>
<script>
function select(o){
let preSelect;
let radios = document.querySelectorAll("input[type='radio']");
for (const radio of radios) {
if(radio.checked){
preSelect = radio.id;
}
}
let bro = o.previousElementSibling;
o.setAttribute("for", bro.id);
let id = o.getAttribute("for");
if(id == preSelect){
return;
}
let preFor = id;
o.removeAttribute("for");
if(confirm("确定要更改吗?")){
console.log("是的");
o.setAttribute("for", preFor);
}else{
console.log("我后悔了");
}
}
</script>
Attention:这个事件是添加到label
标签上的,所以当你点击单选框的按钮时,并不会有这样的效果,只有点击对应label
时才会生效
2020/12/29更新,我又踩坑了,这个单选框真真是折磨我呀
上述代码在使用ajax
与后端进行异步交互传数据的时候不适用,但是呢?把异步的方式改成同步的方式就可以了
看看代码吧:
跟上面的差不多,不用全部理解,这是我大作业项目里的代码,就是把async
设置成false
,改成同步的方式就行了。
function select(o){
let preSelect;
let bro = o.previousElementSibling;
let radios = document.querySelectorAll(`input[name=${bro.name}]`);
for (const radio of radios) {
if(radio.checked){
preSelect = radio.id;
}
}
o.setAttribute("for", bro.id);
let flag = o.innerText;
let currentFor = o.getAttribute("for");
o.removeAttribute("for");
const pisopen = flag == "开放" ? 1 : 0;
const pid = o.getAttribute("pid");
//这里要拿到选中的单选框的id
if(currentFor == preSelect){
return;
}else {
if(confirm("确定更改该职位的发布状态吗?")){
$.ajax({
type: "post",
url: "/company/updateJobStatus",
async: false,
data: {
"pisopen": pisopen,
"pid": pid
},
success: function (res, code){
o.setAttribute("for", currentFor);
for (const val of radios) {
const cflag = val.value;
if(cflag != res){
val.parentElement.style.borderColor = "#9fa3b0";
continue;
}
val.parentElement.style.borderColor = "#53cac3";
}
},
error: function (){
alert("服务器出错了,请待会再试!");
}
})
}else {
return;
}
}
}