从jQuery Autocomplete Widget Ajax调用中访问$(this)DOM元素
在下面的代码(Coffeescript)中,在AJAX调用jQuery自动完成数据源,在代码的第5行,我传递了2个参数 – term:和ll:对于ll:我正在尝试获取$(this)是.autocomplete应用于的DOM元素。 在这种情况下,它的$('[type =“text”] [name * =“[location]”]’)我需要在第5行专门用($ this)引用那个DOM元素。不过,我相信’这个’在该范围内指的是不是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) -> $("").data("item.autocomplete", item).append("" + item.label + "
" + item.address + "").appendTo ul
我不能告诉你关于Coffeescript的任何信息,但是this.element
应该返回元素(它是一个jQuery对象)
所以它应该是:
ll:this.element.siblings('[name*="[geocode_location]"]')
但这不起作用,因为兄弟姐妹返回一个jQuery对象,不能作为请求参数传递。
你错过了自动完成function中的花括号,而你的选择器在我的测试用例中不起作用..
试试这个jQuery选择器:
$('input[type="text"][name*="location"]').autocomplete({ ....
就像@ Dr.Molle建议的那样,this.element有助于获得我想要的DOM元素。 下面更新了代码块。 请参阅第5行,了解我如何应用它。
$('[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) -> $("").data("item.autocomplete", item).append("" + item.label + "
" + item.address + "").appendTo ul