Coffeescript jQuery each loop
Coffeescript jQuery each loop
我对Coffeescrapt还比较陌生,遇到了一些问题,我认为这些问题与瘦箭vs胖箭有关/''uthis vs this vs$(this)。
我有以下类和构造函数:
class @scenarioEditPage
constructor: ->
@getParentAttributes()
并且@getParentAttributes()是
getParentAttributes: ->
@properties = {}
$("#form_configurable").find('input[type=hidden]').each (index, element) =>
@properties[$(element).attr('id')] = element.val()
从本质上讲,我试图做的是循环遍历表单中的所有隐藏字段,并将它们的值分配给属性哈希中的键/值对,以便稍后使用。示例:具有id=some_id
和value=some_value
的隐藏输入字段变为properties[some_id] = some_value
。
如有任何帮助,我们将不胜感激。非常感谢。
首先,除非迫不得已,否则我不会使用class @scenariosEditPage
。class ScenariosEditPage
会更好。
试试这样的方法:http://jsfiddle.net/y6bgrfn2/
class Test
constructor: () ->
@data = {}
@loadData()
loadData: ->
$inputs = $("#container input").each (index, elem) =>
$elem = $ elem
@data[$elem.attr('id')] = $elem.val()
getData: -> @data
$(document).ready () ->
test = new Test()
console.log test.getData()
jQuery的each
方法更改了内部代码的上下文,所以基本上你必须使用双箭头来保留上下文,或者使用带有额外变量的简单箭头,例如ctx = @
,检查这个:
# We have some method @doAnything, so :
@doAnything
# isnt undefined...
# Now:
# this works
$('selector...').each (index, elem) =>
# @ == this == caller's context
@doAnything $(elem)
# or this works fine
ctx = @
$('selector...').each () ->
# this == DOM Element
# ctx == caller's context
# ! ctx isnt @ !
ctx.doAnything $(this)
# this doesnt work
$('selector...').each () =>
# @ == DOM Element, so @doAnything is undefined
@doAnything $(this)
你的代码中有一个小错误:
@properties[$(element).attr('id')] = element.val()
element.val()是undefined
,修复如下:
@properties[$(element).attr('id')] = $(element).val()
或更好:
$element = $ element
@properties[$element.attr('id')] = $element.val()
相关文章:
- jquery.each(第2行)添加背景色
- 如何使用jQuery each分离字符串中的元素
- 对于loop.if-仅在经过所有间隔后返回true
- jQuery setTimeOut: in for-loop
- {{#each}}内部的Handlebar帮助程序
- 为什么我可以在Array属性对象中找到Javascript Array for Each方法
- Jquery.each数组推送不起作用
- 调用$.each()函数时上下文发生变化
- 鉴于 for..在构造中,库提供的函数(如 jQuery.map() 或 _.each())有什么用
- javascript/angularjs 将 String 与 number for loop 连接起来
- Underscore each to update collection
- Coffeescript jQuery each loop
- JavaScript for(-each) loop
- jQuery $.each loop and json mysql data
- jQuery each function parseInt loop
- Loop jQuery for each child
- 对于Loop/Each Loop变量存储和比较(jQuery或Javascript
- Jquery:for loop or $.each
- jquery .each() loop
- 如何将数据存储在 javascript for each “loop” 中,以便可以在“循环”之外访问它