这是我的代码:
document.getElementById("frequencyweekly").checked = function() {
document.getElementById("newsoptions").className = "activesubscription";
};
<div id="newsoptions">
<input type="radio" id="frequencyweekly" name="newsletterfrequency">
<label for="frequencyweekly">Weekly</label>
<input type="radio" id="frequencymonthly" name="newsletterfrequency">
<label for="frequencymonthly">Monthly</label>
</div>
如果选中#frequencyweekly按钮,我希望我的.newsoptions div有class .activesubscription。我该怎么做?
答案 0 :(得分:2)
checked
是一个布尔值,而不是一个触发函数的事件,所以你可能想要
if ( document.getElementById("frequencyweekly").checked ) {
document.getElementById("newsoptions").className = "activesubscription";
}
如果你想在事件处理程序中使用它,那么
var box = document.getElementById("frequencyweekly"),
elem = document.getElementById("newsoptions");
box.addEventListener('change', function() {
if ( this.checked ) {
elem.classList.add("activesubscription");
} else {
elem.classList.remove("activesubscription");
}
}, false);
答案 1 :(得分:0)
如果您想在点击框时执行某些操作,请使用onclick
属性。在其中,您可以查看checked
属性。
document.getElementById("frequencyweekly").onclick = function() {
if (this.checked) {
document.getElementById("newsoptions").className = "activesubscription";
} else {
document.getElementById("newsoptions").className = "";
}
}