检测在jquery中单击了哪个下拉框

时间:2013-02-06 09:39:01

标签: javascript jquery

我正在使用id: assignee, status , priority在多个下拉框中执行相同的功能。

$("#assignee , #status , #priority").change(function() { 

//text here

}

但我想知道点击了哪个特定的下拉列表。有没有办法做到这一点?

5 个答案:

答案 0 :(得分:2)

只需使用以下内容:

$("#assignee, #status, #priority").change(function() { 
    if (this.id === "assignee") { ... }
});

答案 1 :(得分:2)

使用它。在任何事件处理程序中,这都指向发生实际事件的元素:

$("#assignee , #status , #priority").change(function() { 
    var changedElementID = $(this).attr("id");
}

另一种选择是使用event.target

$("#assignee , #status , #priority").change(function(e) { 
        var changedElementID = $(e.target).attr("id");
    }

here您可以找到有关其他事件对象属性的更多详细信息。

请注意,thise.target都是DOM对象,而不是jQuery对象。所以你需要像上面的代码一样用jquery包装它来使用jQuery函数。如果只是获取ID,您可以直接使用this.ide.target.id,这样会更快。

答案 2 :(得分:1)

当事件被触发时,事件处理函数this内部引用触发事件的元素,因此:

$('#assignee, #status, #priority').change(function(e) {
    // Use 'this' to refer to the element that triggered the event
    console.log(this.id);
    // will output assignee, status or priority depending on which changed
});

答案 3 :(得分:0)

使用目标:

$("#assignee , #status , #priority").change(function(e) { 
        var changedElementID = $(e.target).attr("id");
    }

答案 4 :(得分:0)

您绑定<option>时将this传递给该函数并使用您自己的代码

$("#assignee , #status , #priority").change(function(boxID) { 
console.log($(boxID).val());    //Gives you the value of the selected drop down


//text here

}