gpt4 book ai didi

javascript - Coffeescript jQuery 每个循环

转载 作者:行者123 更新时间:2023-11-30 12:26:33 25 4
gpt4 key购买 nike

我是 Coffeescript 的新手,遇到了一些我认为与细箭头与粗箭头/_this 与 this 与 $(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_idvalue=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()

关于javascript - Coffeescript jQuery 每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29186616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com