简体   繁体   English

此JavaScript代码有什么问题?

[英]What is wrong with this JavaScript code?

I have two checkboxes name check1 and check2. 我有两个复选框,分别为check1和check2。 I wanted for either one to be disabled if the other one was checked. 如果要检查另一个,我希望其中一个被禁用。 This is what I did: 这是我所做的:

var male = document.getElementById("check1");
var female = document.getElementById("check2");

male.disabled = (female.checked == true) ? true : false;
female.disabled = (male.checked == true) ? true : false;

It does not work at all. 它根本不起作用。 Is the syntax correct. 语法正确吗? What did I do wrong? 我做错了什么?

You need the onchange event, and your code could be tidied up as well. 您需要onchange事件,并且您的代码也可以整理。

var male = document.getElementById("check1"),
    female = document.getElementById("check2");

male.onchange = function() {
    female.disabled = male.checked;
};

female.onchange = function() {
    male.disabled = female.checked;
};

jsFiddle . jsFiddle

Also, shouldn't you be using radio input? 另外,您不应该使用无线电输入吗?

disabled shouldn't be set at all in order to be disabled AFAIK, any value is "truthy" disabled根本不应该设置禁用以便禁用AFAIK,任何值都是“ truthy”

do .removeAttribute('disabled') to not have it disabled. 执行.removeAttribute('disabled')使其不被禁用。

you need to change the state of the other checkbox when one is clicked eg. 例如,您需要更改另一个复选框的状态。 male changed - alter female, and versa verse. 男性改变了-女性改变了,反之亦然。

function maleOnClick(){
    female.checked= !this.checked;
}
function femaleOnClick(){
    male.checked= !this.checked;
}

Anyway why dont you use type="radio" 无论如何,为什么不使用type="radio"

Try: 尝试:

 male.setAttribute('disabled', 'disabled'); //set
 male.setAttribute('disabled', ''); //clear

So: 所以:

male.setAttribute = (female.checked == true) ? 'disabled': '';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM