我对 jQuery 很陌生,所以如果我错过了一些明显的东西,我深表歉意,但是......我只想在用户单击复选框时隐藏表单的一部分。
所以,我写了这个小 jQuery 脚本:
$("#belonging_entire_world").toggle(function() {
$("#access_for_friends, #access_for_groups").fadeOut();
}, function(){
$("#access_for_friends, #access_for_groups").fadeIn();
});
当我单击标有 id“belonging_entire_world”的复选框时,它确实隐藏了我想要的表单部分(由 #access_for_friends 和 #access_for_groups 表示的部分),如果我再次单击,它会再次显示该部分,但是我选中的复选框“belonging_entire_world”始终在视觉上保持未选中状态...
如果我在脚本运行后打开 firebug,我会看到我的复选框确实具有checked=checked 属性...不过,它在浏览器中看起来未选中(在所有浏览器中!)...
我尝试在切换功能的第一个功能中添加以下内容:
$("#belonging_entire_world").attr('checked', true);
但仍然......它仍然像是未经检查......
这让我发疯,我没有看到另一个删除 jQuery 代码的选项,我真的不明白......我把 View 的一部分放在下面:
<div id="Belonging-Access-Control">
<h2> Who will be able to see & access this? </h2>
<div class="field" id="entire_world">
<%= f.check_box(:entire_world) %>
<%= f.label(:entire_world, "The entire world!") %>
</div>
<div class="field" id="access_for_friends">
<%= f.check_box(:access_for_friends) %>
<%= f.label(:access_for_friends, "My friends") %>
</div>
以及页面的 HTML,在我选中复选框后(firebug 输出):
<div id="Belonging-Access-Control">
<h2> Who will be able to see & access this? </h2>
<div id="entire_world" class="field">
<input type="hidden" value="0" name="belonging[entire_world]">
<input id="belonging_entire_world" type="checkbox" value="1" name="belonging[entire_world]" checked="checked">
<label for="belonging_entire_world">The entire world!</label>
</div>
<div id="access_for_friends" class="field" style="display: none;">
<input type="hidden" value="0" name="belonging[access_for_friends]">
<input id="belonging_access_for_friends" type="checkbox" value="1" name="belonging[access_for_friends]">
<label for="belonging_access_for_friends">My friends</label>
</div>
最佳答案
使用 .toggle() 似乎有问题。如果你用这个功能可以吗?:
$("#belonging_entire_world").click(function() {
if (this.checked) {
$("#access_for_friends, #access_for_groups").fadeOut();
} else {
$("#access_for_friends, #access_for_groups").fadeIn();
}
});
如果您想要相反的淡入淡出,您可以切换淡入淡出。如果复选框以“已选中”开头,这可能是一个更好的解决方案。因此,此代码将根据复选框的状态隐藏/显示其他 div,而不是根据切换它所处的阶段来隐藏/显示其他 div。
关于jquery - 复选框显示为未选中状态,尽管已选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227636/