jquery将控制id传递给内部方法

时间:2010-09-01 16:26:34

标签: jquery ajax

我正在从下拉列表更改处理程序进行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 个答案:

答案 0 :(得分:2)

您可以使用this,只需添加context option of $.ajax()即可this有用:

$('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);
      }  
   });
});

答案 1 :(得分:1)

...
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);

    }  
    ...

答案 2 :(得分:0)

如果您不坚持使用AJAX,您只需将下拉列表的AutoPostback属性设置为true,并在后面的代码中处理已更改的事件。