是否可以在jquery中获取(this)对象的值.attr()?
警报(this)会返回true[object HTMLInputElement]
,因此==
无法正常工作
$("#tag1, #tag2").keyup(function(event){
if(this == "#tag1"){
alert("This is tag1");
};
if(this == "#tag2"){
alert("This is tag1");
};
THX 领域
答案 0 :(得分:4)
无法获得导致当前元素匹配的选择器 - 给定元素有许多可能的选择器。虽然理论上如果$("#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");
}
});
如果这两个元素根本没有公共代码,那么使用两个选择器和函数要好得多,而不是将所有内容放在一个函数中。
答案 1 :(得分:2)
您可以使用this.id
(可能是首选)比较ID,或使用jQuery's is()
方法;
$("#tag1, #tag2").keyup(function (event) {
if (this.id == "tag1") {
alert("This is tag1");
};
if (this.id == "tag2") {
alert("This is tag2");
};
...或
$("#tag1, #tag2").keyup(function (event) {
if ($(this).is("#tag1")) {
alert("This is tag1");
};
if ($(this).is("#tag2")) {
alert("This is tag2");
};
答案 2 :(得分:1)
你想要这个吗? :
$("#tag1, #tag2").keyup(function(event){
alert("This is" + $(this).attr('id'));
});
答案 3 :(得分:0)
你也可以使用开关
$("#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;
}
});