简体   繁体   English

coffeescript,jquery中的每个循环

[英]each loop in coffeescript, jquery

I'm new to javascript and starting the mix javascript + jquery + coffeescript all together is not easy for a newbie like me... 我是javascript的新手并且开始混合javascript + jquery + coffeescript一起对我这样的新手来说并不容易...

I've created a very simple sortable list and I'd like to renumber my list on the fly (the server side code is ok). 我创建了一个非常简单的可排序列表,我想动态重新编号我的列表(服务器端代码没问题)。

The coffeescript code I wrote is: 我写的coffeescript代码是:

jQuery ->
  $('.simple_grid tbody').sortable
    axis: 'y'
    containment: 'parent'
    cursor: 'move'
    tolerance: 'pointer'
    update: (event,ui)->
      $.post($(this).attr('dataupdateurl') + '/' + ui.item.attr('id') + '/reorder/' + ui.item.index())
      $('tr > td > a > span.number').each (i, element)  =>
      $(element).html i

This generates a table of this kind 这会生成一个这样的表

<table class= "simple-grid">
   <tbody dataupdateurl = "xxx">
      <tr>
         <td>
            <a href="some_link"><span class="number">1</span>text 1</a>
         </td>
          <td>
            <a href="some_link"><span class="number">2</span>text 2</a>
         </td>
        <td>
            <a href="some_link"><span class="number">3</span>text 3</a>
         </td>
      </tr>
   </tbody>
</table>

I'm trying to renumber what's inside the span.number elements when the update callback triggers but I get following error message: 我正在尝试重新编号更新回调触发时span.number元素内的内容,但我收到以下错误消息:

element is not defined 元素未定义

Any help would be very welcome! 非常欢迎任何帮助! Thanks! 谢谢!

UPDATE: the problem was due to the fact that I missed an indent in the last function: 更新:问题是由于我错过了最后一个函数的缩进:

$('span.number').each (i, element)  =>
      $(element).html i

I don't know coffee script but generally using jQuery selector doesn't require the full path. 我不知道咖啡脚本,但一般使用jQuery选择器不需要完整的路径。 eg $('tr > td > a > span.number') could be rewritten as $('.number') , also the .each() is generally used as .each(function(index, element) { YOUR CODE }); 例如$('tr > td > a > span.number')可以重写为$('.number') ,同样.each()通常用作.each(function(index, element) { YOUR CODE }); . The last thing that looks out of place is setting the html this is generally done as .html('value') . 最后看起来不合适的是设置html,这通常是以.html('value') So in your case $(element).html(i); 所以在你的情况下$(element).html(i); . Hope this helps? 希望这可以帮助?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM