在Rails中,我有一个表格,可以一次编辑多个记录。我只想在勾选复选框时显示一些元素。这是我写的javascript:
<script type="text/javascript">
$(document).ready(function() {
// Initially if free is checked hide nonfree options else show
if ($('<%= "#submits_#{submitid}_free" %>').attr('value') == '1') {
$('<%= "#submits_#{submitid}_revealnonfree" %>').hide();
} else {
$('<%= "#submits_#{submitid}_revealnonfree" %>').show();
}
// Initiall if sell rights is checked show prices or else hide
if ($('<%= "#submits_#{submitid}_sellrights" %>').attr('value') == '1') {
$('<%= "#submits_#{submitid}_revealrights" %>').show();
} else {
$('<%= "#submits_#{submitid}_revealrights" %>').hide();
}
// If free checked hide nonfree
$('<%= "#submits_#{submitid}_free" %>').change(function() {
if (this.checked) {
$('<%= "#submits_#{submitid}_revealnonfree" %>').fadeOut('slow');
} else {
$('<%= "#submits_#{submitid}_revealnonfree" %>').fadeIn('slow');
}
});
//If sell rights checked show prices
$('<%= "#submits_#{submitid}_sellrights" %>').change(function() {
if (this.checked) {
$('<%= "#submits_#{submitid}_revealrights" %>').fadeIn('slow');
} else {
$('<%= "#submits_#{submitid}_revealrights" %>').fadeOut('slow');
}
});
});
</script>
我在每条记录后加载它。当更改正确的复选框值时,脚本会隐藏和取消隐藏元素。但是,如果在页面加载时勾选了复选框,则脚本不会显示必要的元素。脚本的第一部分应该这样做,但它没有。这是我没有脚本的表单源代码:http://pastebin.com/Vj9HbrEB
答案 0 :(得分:1)
只需为每个复选框触发一次更改事件,并将其添加到脚本的末尾:
$('<%= "#submits_#{submitid}_free" %>').trigger('change')
$('<%= "#submits_#{submitid}_sellrights" %>').trigger('change')