Javascript 如何测试元素是否具有特定的类?
我有如下函数刷新其数据,如下所示Javascript 如何测试元素是否具有特定的类?,javascript,jquery,Javascript,Jquery,我有如下函数刷新其数据,如下所示 refresh: function($contentholder) { $contentholder.each(function() { $this = $(this); if ($this.hasClass("Codes")) { //then it does some stuff in here } } } <div class="Codes" cod=
refresh: function($contentholder) {
$contentholder.each(function() {
$this = $(this);
if ($this.hasClass("Codes")) {
//then it does some stuff in here
}
}
}
<div class="Codes" cod="t592">
<h3></h3>
<div class="Items">
<div class="ItemCodes" id="592" time="2016/04/30 12:15" places="1"></div>
</div>
</div>
$contentholder
包含以下数据
refresh: function($contentholder) {
$contentholder.each(function() {
$this = $(this);
if ($this.hasClass("Codes")) {
//then it does some stuff in here
}
}
}
<div class="Codes" cod="t592">
<h3></h3>
<div class="Items">
<div class="ItemCodes" id="592" time="2016/04/30 12:15" places="1"></div>
</div>
</div>
基本上,我想做这样的事情
if ($this.hasClass("Codes").find("ItemCodes"))
如何实现这一点?您可以使用find()
来确定是否存在任何子.ItemCodes
元素。您将需要两个单独的条件,因为这些语句不能合并
刷新:函数($contentholder){
$contentholder.each(函数(){
$this=$(this);
if($this.hasClass(“code”)和&$this.find('.ItemCodes').length){
//在这里做些事情
}
}
}
您可以将.is()
方法与:has()
伪选择器组合使用,如下所示:
if ( $this.is('.Codes:has(".ItemCodes")') ) {
//
}
let$that=$('div.Codes');
console.log($that.is('.code:has(“.ItemCodes”));
我已经尝试过这个方法,但是现在如果没有“itemcodes”出现,它仍然会进入if语句,因此它实际上不会检查它是否在if语句中。我无法复制这种行为,上面的代码起作用:没问题,很乐意帮助:)