Javascript 如何在jQuery中识别所选的选择器? $('#选择#id1,#选择#id2,#选择#id3')。更改(函数(){ //如果“#选择_id1”已更改,“str”应等于“选择_id1”。 //如果“#选择_id2”已更改,“str”应等于“选择_id2”。 //如果“#选择_id3”已更改,“str”应等于“选择_id3”。 str= });

Javascript 如何在jQuery中识别所选的选择器? $('#选择#id1,#选择#id2,#选择#id3')。更改(函数(){ //如果“#选择_id1”已更改,“str”应等于“选择_id1”。 //如果“#选择_id2”已更改,“str”应等于“选择_id2”。 //如果“#选择_id3”已更改,“str”应等于“选择_id3”。 str= });,javascript,jquery,Javascript,Jquery,您可以通过this.id获取调用更改的元素的id $('#select_id1, #select_id2, #select_id3').change(function() { // If '#select_id1' has changed, 'str' should be equal to 'select_id1'. // If '#select_id2' has changed, 'str' should be equal to 'select_id2'. // If

您可以通过
this.id
获取调用更改的元素的id

$('#select_id1, #select_id2, #select_id3').change(function() {
    // If '#select_id1' has changed, 'str' should be equal to 'select_id1'.
    // If '#select_id2' has changed, 'str' should be equal to 'select_id2'.
    // If '#select_id3' has changed, 'str' should be equal to 'select_id3'.
    str = <what should be here ?>
});
或(效率较低):


但基本上,
设置为事件发生的元素。

您可以通过传入的事件对象直接或间接查看
此.id

$('#select_id1, #select_id2, #select_id3').change(function() {
  str = $(this).attr("id");
});

大多数人只关注
这一点
,但有时您可能对活动的目标感兴趣。

对于更一般的情况,如@Anurag所建议的,不仅使用ID,您还可以执行以下操作:

$('#select_id1, #select_id2, #select_id3').change(function (e) {
    alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id));
});

如果您想要添加更改处理程序的选择器,那么您必须做更多的工作。一个例子是,如果可以使用id以外的条件选择select元素-
$(“.select1,#select2,div>.select3”)
确实没有理由使用此选项-在直接获取DOM属性时使用jQuery可能效率极低,应该加以劝阻。
$('#select_id1, #select_id2, #select_id3').change(function (e) {
    alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id));
});
// Save the selector
var selector = ".someClass, #someId, tr.someTrClass";

$(selector).change(function () {
    var selectors = selector.split(","),
        matching = []; // Remember that each element can
                       // match more than one selector
    for (var i = 0, s; s = selectors[i]; i++) {
        if ($(this).is(s)) matching.push(s);
    }

    str = matching.join(","); // Your list of all matching selectors
});