我见过类似的问题,例如“How do I toggle an element's class in pure JavaScript?”,但这个问题是指属性。
我有一个像这样的复选框:
<span class="newsletter-checkbox">
<input type="checkbox" name="newsletter" id="newsletter" checked> Sign up to the newsletter as well - recieve new posts in your inbox
</span>
如何点击.newsletter-checkbox
(包括文字)中的任何位置,它会切换复选框checked
属性?
答案 0 :(得分:0)
只需使用:
function toggleCheckbox() {
var checkbox = document.getElementById('newsletter');
checkbox.checked = !checkbox.checked;
}
<span class="newsletter-checkbox" onclick="toggleCheckbox()"><input type="checkbox" name="newsletter" id="newsletter" checked> Sign up to the newsletter as well - recieve new posts in your inbox</span>