jquery如何从多个选择器获取(this)的值

jquery如何从多个选择器获取(this)的值,jquery,this,attr,Jquery,This,Attr,在jquery中是否可以获取此对象的值.attr alertthis返回true[object HTMLInputElement],因此==将不起作用 $("#tag1, #tag2").keyup(function(event){ if(this == "#tag1"){ alert("This is tag1"); }; if(this == "#tag2"){ alert("Th

在jquery中是否可以获取此对象的值.attr

alertthis返回true[object HTMLInputElement],因此==将不起作用

  $("#tag1, #tag2").keyup(function(event){
         if(this == "#tag1"){
            alert("This is tag1");
            };
         if(this == "#tag2"){
            alert("This is tag1");
                };      
thx
Art

无法获取导致当前元素匹配的选择器-给定元素有许多可能的选择器。虽然从理论上讲,如果$tag1、tag2创建的jQuery对象仍然可用,那么它将非常丑陋

但是,您可以简单地使用this.id访问您案例中元素的id“tag1”或“tag2”,并在代码中使用它:

$("#tag1, #tag2").keyup(function(event) {
    if(this.id == "tag1") {
        alert("This is tag1");
    }
    if(this.id == "tag2") {
        alert("This is tag1");
    }
});

如果这两个元素根本没有通用代码,那么最好使用两个选择器和函数,而不是将所有内容都放在一个函数中。

您可以使用此方法比较id。可能首选id,或者使用方法

或者

你想要这个

$("#tag1, #tag2").keyup(function(event){
     alert("This is" + $(this).attr('id'));
});
你也可以使用开关

$("#tag1, #tag2").keyup(function(event){
  target = $(this).attr('id');
     switch(target) {
     case:"#tag1"
        alert("This is tag1");
        break;
     case:"#tag2"
        alert("This is tag2");
        break;
      }
 });

哥们,当你必须为tag1和tag2做不同的事情时,为什么不为它们使用单独的代码块呢?给出正确的答案,你的回答最快。也可以使用这个。名称,thx to all用于快速回复名称不一定是唯一的,因此使用ID通常更好。特别是如果仍然按ID选择元素。
$("#tag1, #tag2").keyup(function(event){
     alert("This is" + $(this).attr('id'));
});
$("#tag1, #tag2").keyup(function(event){
  target = $(this).attr('id');
     switch(target) {
     case:"#tag1"
        alert("This is tag1");
        break;
     case:"#tag2"
        alert("This is tag2");
        break;
      }
 });