2014-01-24 87 views
0

我不完全确定如何对这个问题进行短语,所以如果不清楚,请致歉。我有这样的代码,当3个下拉菜单中的任何一个改变运行的AJAX查询:如何识别多重选择器功能中的特定选择器?

$('#ass-seenByName, #ass-seenByName1, #ass-seenByName2').change(function() { 
    $.ajax({ 
    type: "GET", 
    url: "getMDSSpeciality.php", 
    data: { "mds_name": $(this).val() }, 
    async: false, 
    success: function(msg){ 
     alert("Hello " + msg); 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
     databaseError({ 
     title: "Database error", 
     string: "Unable to get speciality for selected individual", 
     file: window.location.pathname, 
     actualError: errorThrown 
     }); 
    } 
    }); 
}); 

返回msg值需要去3的一个领域取决于已更改特定下拉菜单。我的问题是我不知道如何获得3个可能的下拉菜单中的哪一个在jQuery中被更改,而没有为每个单独的下拉菜单重复该代码块3次。

回答

3

您可以使用this在事件处理中引用其触发处理程序的元素,这样你就可以创建一个闭包变量,它是指在可以在成功处理程序可以用来设置该消息的单击处理元素

$('#ass-seenByName, #ass-seenByName1, #ass-seenByName2').change(function() { 
    var $this = $(this); 
    $.ajax({ 
     type: "GET", 
     url: "getMDSSpeciality.php", 
     data: { 
      "mds_name": $(this).val() 
     }, 
     async: false, 
     success: function (msg) { 
      alert("Hello " + msg); 
      $this.html(msg) 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      databaseError({ 
       title: "Database error", 
       string: "Unable to get speciality for selected individual", 
       file: window.location.pathname, 
       actualError: errorThrown 
      }); 
     } 
    }); 
}); 
+0

谢谢,对不起,我没有搞清楚,但我不知道希望结果与t相同他选择。我希望它能够转到选择器的3个完全不同的字段之一,但具体的字段取决于所使用的选择器。 – Roy

+0

@Roy然后你需要分享如何使用clicked元素找到3个不同的字段......一个示例html标记将使我们更容易 –

+0

没关系Arun,我想通了$ this.attr(' id')来获得选择器的id,然后从那里使用switch语句。感谢您的帮助,我会将您的答案标记为可选! – Roy

0

是,使用“本”,如果你想将追加到选择的选项, 试试这个,

$('#ass-seenByName, #ass-seenByName1, #ass-seenByName2').change(function() { 
    $.ajax({ 
     type: "GET", 
     url: "getMDSSpeciality.php", 
     data: { 
      "mds_name": $(this).val() 
     }, 
     async: false, 
     success: function (msg) { 
      $(this).empty();//empties the select 
      $(this).append($('<option>').text(msg).attr('value', msg));//appends to options    
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
      databaseError({ 
       title: "Database error", 
       string: "Unable to get speciality for selected individual", 
       file: window.location.pathname, 
       actualError: errorThrown 
      }); 
     } 
    }); 
}); 
相关问题