簡體   English   中英

從jQuery Autocomplete Widget Ajax調用中訪問$(this)DOM元素

[英]Access $(this) DOM element from within jQuery Autocomplete Widget Ajax call

在下面的代碼(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的任何信息,但是this.element應該返回element(這是一個jQuery對象)

所以應該是:

ll:this.element.siblings('[name*="[geocode_location]"]')

但這是行不通的,因為同級返回一個jQuery對象,並且不能作為請求參數傳遞。

您在自動完成功能中缺少大括號,並且選擇器在我的測試用例中不起作用。

試試這個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) ->
    $("<li>").data("item.autocomplete", item).append("<a>" + item.label + "<br>" + item.address + "</a>").appendTo ul

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM