Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取$的类名(此)_Javascript_Jquery - Fatal编程技术网

Javascript 获取$的类名(此)

Javascript 获取$的类名(此),javascript,jquery,Javascript,Jquery,我有$(“#通知列表,.opt#通知家长”),然后我使用$(此)。现在我需要检查$(this)是第一个选择器还是第二个选择器。 我该怎么做 我尝试过类似的方法,但不起作用: if ($(this) == 'opt_notifications_parent'){ console.log("test"); } 你可以用 或者(这是一个更昂贵的操作,所以请使用hasClass) 你可以用 或者(这是一个更昂贵的操作,所以请使用hasClass) 可以使用is() 可以使用is() 在jQue

我有
$(“#通知列表,.opt#通知家长”)
,然后我使用
$(此)
。现在我需要检查
$(this)
是第一个选择器还是第二个选择器。 我该怎么做

我尝试过类似的方法,但不起作用:

if ($(this) == 'opt_notifications_parent'){
    console.log("test");
}
你可以用

或者(这是一个更昂贵的操作,所以请使用hasClass)

你可以用

或者(这是一个更昂贵的操作,所以请使用hasClass)

可以使用
is()

可以使用
is()


在jQuery中,最简单的方法是:

if ($(this).is('#notifications_list')) {
  // ...
} else if ($(this).is('.opt_notifications_parent')) {
  // ...
}
或者,您可以用JavaScript的方式来完成,这应该会快一点:

if (this.id == 'notifications_list') {
  // ...
} else if (-1 !== Array.prototype.indexOf.call(this.classList, 'opt_notifications_parent') {
  // ...
}

在jQuery中,最简单的方法是:

if ($(this).is('#notifications_list')) {
  // ...
} else if ($(this).is('.opt_notifications_parent')) {
  // ...
}
或者,您可以用JavaScript的方式来完成,这应该会快一点:

if (this.id == 'notifications_list') {
  // ...
} else if (-1 !== Array.prototype.indexOf.call(this.classList, 'opt_notifications_parent') {
  // ...
}

如果您在事件关闭中,可以执行以下操作:

$("#notifications_list, .opt_notifications_parent").on('click', function(e) {
    if ($(this).is('#notifications_list')) {
        // first selector clicked.
    } else {
        // other selector clicked.
    }
});

如果您在事件关闭中,可以执行以下操作:

$("#notifications_list, .opt_notifications_parent").on('click', function(e) {
    if ($(this).is('#notifications_list')) {
        // first selector clicked.
    } else {
        // other selector clicked.
    }
});

这样做的问题是,元素可能是对的。所以我建议只在单个选择器中使用任意一类ID。问题是,元素可能同时是
@right。因此,我建议只在单个选择器中使用任何一类ID。请首先仔细检查ID,因为所讨论的元素可能同时具有ID和IDclass@Phil当前位置如果我们从另一个方向进行检查,它仍然可以同时拥有这两种功能。我主要是演示测试本身;这取决于特定的用例和OP所需的应用程序逻辑。是的,但如果分支逻辑围绕元素是否具有类(这似乎是最有可能的情况)进行,这应该在
if
中,而不是
else if
中,首先仔细检查ID,因为相关元素可能同时具有ID和IDclass@Phil当前位置如果我们从另一个方向进行检查,它仍然可以同时拥有这两种功能。我主要是演示测试本身;这取决于特定用例和OP所需的应用程序逻辑。是的,但如果分支逻辑围绕元素是否具有类(这似乎是最有可能的情况),则应该在
if
中,而不是
else if