JavaScript CoffeScript 函数末尾 return 的问题

changwu · 2013年03月20日 · 最后由 changwu 回复于 2013年03月20日 · 2890 次阅读

刚接触 coffeescript,在写全选功能时遇到问题,请大佬们帮忙解决一下。 coffeescript:

jQuery ->
  toggle1 = true
  $('.checkall').click ->
    if toggle1
      $('.checkone').each -> $(this).checked = "yes" 
    else
      $('.checkone').each -> $(this).checked = null  
    toggle1 = !toggle1

生成的 javacript:

(function() {

  jQuery(function() {
    var toggle1;
    toggle1 = true;
    return $('.checkall').click(function() {
      if (toggle1) {
        $('.checkone').each(function() {
          return $(this).checked = "yes";
        });
      } else {
        $('.checkone').each(function() {
          return $(this).checked = null;
        });
      }
      return toggle1 = !toggle1;
    });
  });

}).call(this);

为毛老加个 return 啊??return 后就没执行了,所以全选功能就诡异了。。求明白人指点下,先谢了!!

CoffeeScript 会自动给函数最后一行作为 return 的,如果你不想那样,可以手工写个 return

此外,你这标题应该叫 CoffeeScript return 的问题啊,和全选有啥关系

可以这样赋值的吗?! $(this).checked = null

最后一行自己写个 true 或者 false

jQuery ->
  $('.checkall').click ->
    if $(this).is(':checked')
      $('.checkone').each -> $(this).checked = "yes" 
    else
      $('.checkone').each -> $(this).checked = null

$(this).checked 可以?

$(this).prop("checked", true) or $(this)[0].checked = "yes"

谢谢各位,我发现用$('.checkone').each -> $(this).attr('checked', true) 在第一次选择时可以,第二三次就不行(这也是我为什么认为 return 的问题),是不是 jquery 版本问题?我用的是 1.9.1。以下代码经测试都可以: 1.

jQuery ->
  $('.checkall').click -> 
    if $(this).prop('checked')
      $('.checkone').each -> $(this).prop('checked', true)
    else
      $('.checkone').each -> $(this).prop('checked', false)

2.

jQuery ->
  $('.checkall').click -> 
    if $(this).prop('checked')
      $('.checkone').each -> $(this)[0].checked = "yes"
    else
      $('.checkone').each -> $(this)[0].checked = null

2 的执行效率是最高的,可以看这里:http://jsperf.com/prop-vs-ischecked/5

#6 楼 @krazy #5 楼 @lgn21st 谢谢牛亲,最后求推荐本 JQuery 的书。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号