CoffeeScript、jquery 中的每个循环
我是 javascript 新手,对于像我这样的新手来说,开始混合 javascript + jquery + Coffeescript 并不容易......
我创建了一个非常简单的可排序列表,我想动态重新编号我的列表(服务器端代码没问题)。
我编写的 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
这会生成一个此类表格,
<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>
当更新回调触发时,我试图对 span.number 元素内的内容重新编号,但收到以下错误消息:
元素未定义
非常欢迎任何帮助!谢谢!
更新:问题是由于我错过了最后一个函数中的缩进:
$('span.number').each (i, element) =>
$(element).html i
I'm new to javascript and starting the mix javascript + jquery + coffeescript all together is not easy for a newbie like me...
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:
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:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道咖啡脚本,但通常使用 jQuery 选择器不需要完整路径。
例如
$('tr > td > a > span.number')
可以重写为$('.number')
,也是 .each()通常用作.each(function(index, element) { YOUR CODE });
。最后一件看起来不合适的事情是设置 html,这通常是通过.html('value')
完成的。所以在你的情况下$(element).html(i);
。希望这有帮助吗?I don't know coffee script but generally using jQuery selector doesn't require the full path.
e.g.
$('tr > td > a > span.number')
could be rewritten as$('.number')
, also the .each() is generally used as.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')
. So in your case$(element).html(i);
. Hope this helps?