【发布时间】:2012-11-01 20:55:42
【问题描述】:
在下面的代码 (Coffeescript) 中,在 jQuery 自动完成数据源的 AJAX 调用中,在代码的第 5 行,我传递了 2 个参数 - term: 和 ll: 对于 ll:我试图让 $(this) 成为应用 .autocomplete 的 DOM 元素。在这种情况下,它的 $('[type="text"][name*="[location]"]') 我需要在第 5 行用 ($this) 专门引用该 DOM 元素。但是,我相信该范围内的“this”指的是不是 DOM 元素的其他东西。有人可以帮忙解释我需要做什么吗?
$('[type="text"][name*="[location]"]').autocomplete(
source: (request, response) ->
$.ajax
url: $('[type="text"][name*="[location]"]').data('autocomplete-source')
data: {term: request.term, ll: $(this).siblings('[name*="[geocode_location]"]')}
contentType: "application/json; charset=utf-8"
success: (data) ->
response $.map(data, (item) ->
value: item.value
label: item.label
address: item.address
)
focus: (event, ui) ->
event.preventDefault()
$(this).val ui.item.label
select: (event, ui) ->
event.preventDefault()
$(this).val ui.item.label
$(this).siblings('[name*="[foursquare_id]"]').val ui.item.value
).data("autocomplete")._renderItem = (ul, item) ->
$("<li>").data("item.autocomplete", item).append("<a>" + item.label + "<br>" + item.address + "</a>").appendTo ul
【问题讨论】:
-
您的自动完成参数对象缺少起始大括号。
-
我不知道coffeescript,但快速浏览一下文档表明它省略了许多常见的JS花括号。
-
@Barmar 是正确的,coffeescript 不需要那个花括号。除了我在代码的第 5 行中对 $(this) 的调用之外,一切正常。我知道一切正常,因为我只用一个字符串替换它并且知道它有效。我的问题是围绕 ($this) 的范围,因为在第 5 行, ($this) 没有引用应用自动完成功能的原始 DOM 元素。不过我需要它。
标签: javascript jquery jquery-ui jquery-selectors coffeescript