问题
In the code below (Coffeescript), in the AJAX call for the jQuery autocomplete data source, On line 5 of the code, I am passing 2 params - term: and ll: For ll: I'm trying to get $(this) to be the DOM element that .autocomplete was applied to. In this case its $('[type="text"][name*="[location]"]') I need to reference that DOM element specifically with ($this) on line 5. However, I believe 'this' at that scope refers to something else that isn't a DOM element. Can someone please help explain what I need to do?
$('[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
回答1:
I can't tell you anything about Coffeescript, but this.element
should return the element(it's an jQuery-object)
So it should be:
ll:this.element.siblings('[name*="[geocode_location]"]')
But this will not work, because siblings returns an jQuery-object and could not be passed as a request-parameter.
回答2:
You're missing the curly bracket in the autocomplete function and you're selector isn't working in my test case..
try this jQuery selector:
$('input[type="text"][name*="location"]').autocomplete({ ....
回答3:
like @Dr.Molle suggested, this.element helps to get the DOM element that I wanted. Updated code block below. See the 5th line for how I applied it.
$('[type="text"][name*="[location]"]').autocomplete(
source: (request, response) ->
$.ajax
url: $('[type="text"][name*="[location]"]').data('autocomplete-source')
data: {term: request.term, ll: this.element.siblings('[name*="[geocode_location]"]').val()}
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
来源:https://stackoverflow.com/questions/13185331/access-this-dom-element-from-within-jquery-autocomplete-widget-ajax-call