jQuery如何区分哪个“

问题描述 投票:-1回答:2

我的主要问题是,如何区分哪个下拉框已更改?本质上,我具有下拉框/组合框的HTML代码,该代码由JS中的JSON文件填充。

            <select id="filterCountry">
              <option value="0">All Countries</option>
            </select>
            <select id="filterBrowser">
              <option value="0">All Browsers</option>
            </select>
            <select id="filterOS">
              <option value="0">All Operating System</option>
            </select>

我的jQuery代码现在与此类似。

$("#filterBrowser, #filterOS, #filterCountry").change(function(e){
    alert("Something has been changed "  + this.value);

    // Ugly pseudocode but something along the lines of...
    if(("#filterBrowser").change) {
        console.log("the browser drop down was changed");
    } else if (("#filterOS").change) {
        console.log("The OS drop down changed");
    } else if(("#filterCountry").change) {
        console.log("The country drop down was changed")
    }
});
javascript jquery json html-select onchange
2个回答
0
投票

您可以获取引发事件的元素的ID。例如:

if(this.id === 'filterBrowser') {
  //...
}

0
投票

您可以通过引用this关键字来检查当前下拉列表的id属性:

this
$("#filterBrowser, #filterOS, #filterCountry").change(function(e){
  if(this.id == 'filterBrowser') {
    console.log("the browser drop down was changed");
  } else if (this.id == 'filterOS') {
    console.log("The OS drop down changed");
  } else if(this.id == 'filterCountry') {
    console.log("The country drop down was changed")
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.