Coffeescript 只评估一次

Coffeescript evaluates only once

我想根据 this findle 创建一个 select 全部复选框。我制作了这样的 coffeescript:

$(document).on 'click','.select_all_clans', ->
  if $(this).is(':checked')
    $('.clan_checkbox').attr 'checked', true

但它仅在 check_box.clan_checkbox 之前未被 select 编辑时有效,并且只检查一次。

这是我的表格:

<%= form_tag show_schools_path do %>
 <p>
   Wybierz klan/y: 
   Feniks: <%= check_box_tag 'clans[]','Feniks', (true if !@clans.nil? and @clans.include? 'Feniks'), class: "clan_checkbox" %>,
   Jednorożec: <%= check_box_tag 'clans[]','Jednorożec', (true if !@clans.nil? and @clans.include? 'Jednorożec'), class: "clan_checkbox" %>,
   Krab: <%= check_box_tag 'clans[]', 'Krab', (true if !@clans.nil? and @clans.include? 'Krab'), class: "clan_checkbox" %>,
   Lew: <%= check_box_tag 'clans[]', 'Lew', (true if !@clans.nil? and @clans.include? 'Lew'), class: "clan_checkbox" %>,
   Zaznacz Wszystkie: <%= check_box_tag 'select_all', 'nil', false, class: "select_all_clans" %>
 </p>
<%= submit_tag "Szukaj!" %>
<% end %>

我认为这是因为(true if !@clans.nil? and @clans.include? 'Lew')评估。

我刚刚开始学习 CS,所以如果可能的话请详细解释 :)

给你,我希望这就是你要找的:

boxes = $('#checkboxlist [type=checkbox]')
selectAll = $('.selectall')    
toggleCheckboxes = ->    
    if $(this).is ':checked' then boxes.prop "checked", true else boxes.prop "checked", false

selectAll.on 'click', toggleCheckboxes

Fiddle

您应该将 attr() 更改为 prop()

这里没有发生什么特别的事情,我们刚刚将 toggleCheckboxes() 绑定到 selectAll 元素上的点击事件。

提示:下次为此类问题添加 javascript 标签时,您将更快地获得解决方案,并且稍后可以将其转换回 CS。