【问题标题】:jQuery autocomplete not finding $(this) inside $.ajaxjQuery 自动完成在 $.ajax 中找不到 $(this)
【发布时间】:2014-05-15 14:18:53
【问题描述】:

我有一个 MVC 应用程序,它使用链接 1 中的自动完成功能。然后,为了能够格式化显示,我使用这个 JSON 模式传递了一个复杂的 JSON 对象:

{
   "name": "searchResults",
   "properties": {
        "Id": {
            "type": "number",
            "description": "Table.ID, maps to value",
            "required": true
        },
        "Name": {
            "type": "string",
            "description": "Display name, maps to label",
            "required": true
        },
        "Type": {
            "type": "number",
            "description": "Table selector (enum)",
            "required": true
        }
   }
}

问题是我不能在$.ajax 函数中使用$(this)。我尝试使用上下文,但它不起作用。我不断收到 "SyntaxError: Unexpected token 。下面是 JavaScript 代码:

$(function () {
  $('*[data-autocomplete-url]').each(function () {
    $(this).autocomplete({
      source: function (request, response) {
        $.ajax({
          // THIS WORKS!
          //url: $('*[data-autocomplete-url]').data('autocomplete-url'),
          // THIS DOESN'T WORK!
          url: $(this).data('autocomplete-url'),
          dataType: "json",
          contentType: 'application/json, charset=utf-8',
          data: {
            token: $("#tags").val()
          },
          success: function (data) {
            response($.map(data, function (item) {
              return {
                label: item.Name,
                value: item.Id
              };
            }));
          },
          error: function (xhr, status, error) {
            alert(error);
          }
        });
      },
      select: function (event, ui) {
        $("#tags").val(ui.item.label);
        $("#tagsId").val(ui.item.value);
        event.preventDefault();
      },
      focus: function (event, ui) {
        $("#tags").val(ui.item.label);
        event.preventDefault();
      },
      minLength: 3
    });
  });
});

这是 Razor sn-p:

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" data-autocomplete-url="@Url.Action("Search", "Search")" />
    <input id="tagsId" hidden="hidden" />
</div>

有没有办法使用$(this) 来获取负责触发动作的特定自动完成元素?

参考资料:

ASP.NET MVC & jQuery UI autocomplete

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc razor-2


    【解决方案1】:

    在 ajax 函数 this 中不起作用,因为它没有元素引用的范围。

    您需要在发出 ajax 请求之前存储此副本:

    var url =  $(this).data('autocomplete-url');
    

    并在 ajax 调用中使用该变量:

    url:url
    

    【讨论】:

    • 问题不在于 ajax 方法,而是源回调方法,其中 this 不是指元素,而是指插件本身,因此使用设置为 this 的上下文选项不应该工作 AFAIK
    • 正如@A.Wolff 所说,context 不起作用。但是使用变量可以。
    【解决方案2】:

    each 循环内使用闭包变量或在source 回调方法内使用获取元素:

    url: $(this.element).data('autocomplete-url'),
    

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2013-03-19
      • 1970-01-01
      相关资源
      最近更新 更多