代码之家  ›  专栏  ›  技术社区  ›  Victor

jquery将控件ID传递到内部方法

  •  1
  • Victor  · 技术社区  · 14 年前

    我正在从下拉更改处理程序进行Ajax调用(ASP.NET 3.5),并尝试将下拉ID传递到Ajax调用:

    $('select.facility').change(function()
    {
          if ($(this).val() != 0)
          {
                var params = new Object();
                params.facilityId = $(this).val();
    
                $.ajax(
                    {
                        type: "POST",
                        data: $.toJSON(params),
                        dataType: "json",
                        contentType: "application/json",
                        url: "SomeURL.asmx/SomeMethod",
                        success: function(response)
                        {
                            //this is where I need to get a hold of my dropdown,
                            // $(this) obviously doesn't work, using just to illustrate  
                            $(this).closest('table').next('table')
                            .find('input.address').val(response.d.Address);
    
                        }  
    
          }
    });
    

    有没有优雅的方法?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Nick Craver    14 年前

    你可以使用 this ,只需添加 context option of $.ajax() 所以 是有用的:

    $('select.facility').change(function() {   
       if ($(this).val() == 0) return;
       var params = { facilityId = $(this).val() };
       $.ajax({
          context: this,                           //add this!
          type: "POST",
          data: $.toJSON(params),
          dataType: "json",
          contentType: "application/json",
          url: "SomeURL.asmx/SomeMethod",
          success: function(response) {
            $(this).closest('table').next('table')
                   .find('input.address').val(response.d.Address);
          }  
       });
    });
    
        2
  •  1
  •   karim79    14 年前
    ...
    var parentContext = $(this);
    $.ajax(
    {
        type: "POST",
        data: $.toJSON(params),
        dataType: "json",
        contentType: "application/json",
        url: "SomeURL.asmx/SomeMethod",
        success: function(response)
        {
            //this is where I need to get a hold of my dropdown,
            // $(this) obviously doesn't work, using just to illustrate  
            parentContext.closest('table').next('table')
            .find('input.address').val(response.d.Address);
    
        }  
        ...
    
        3
  •  0
  •   Darin Dimitrov    14 年前

    如果不坚持使用Ajax,只需设置 AutoPostback 属性,并在代码隐藏中处理更改的事件。