我不确定,你说的“它不起作用”是什么意思。所以我猜这个问题并提供一个可能的解决方案…
实际上,它是有效的。但是-您的JS片段只执行一次,
页面加载时
/准备好了。我想,你想要你的
<p>
要切换类的元素
checked
每当复选框被选中或取消选中时。
为此,需要将事件触发器绑定到复选框,这样每次执行JS时,都要选中/取消选中该框。
这样做:
//function to execute on every click event of a checkbox
$("input[type=checkbox]").on("click", function(){
//instead of using .parent().find() you can simply use .siblings() to find the p element
myTextElem = $(this).siblings("p");
// toggle the class
myTextElem.toggleClass("checked");
if(myTextElem.hasClass("checked")){
// here you can do something, if it is checked
} else {
// here you can do something, if it is unchecked
}
});
当然,只有当选中的类和复选框状态处于某种同步状态时,这才有效。因此,使用click函数,实际上,
p
元素将不具有选中的类onload,即使默认选中了复选框。
为此,您需要添加一些代码,以便在DOM上执行:
$("input[type=checkbox]").each(function(){ //loop through all checkboxes
myTextElem = $(this).siblings("p"); //select sibling text elem
if($(this).is(":checked")){ //if checkbox is checked
myTextElem.addClass("checked"); //initially add class checked
}
});