我用代码编写了这个条件。
我不确定它是否可以缩短或优化。还想知道这可以被认为是写CCD_ 1&一次检查几件事。
if(isMobile() && (jQuery("body").hasClass("catalog-category-view") || jQuery("body").hasClass("catalog-product-view") || jQuery("body").hasClass("wishlist-index-index")) && !jQuery('.prev_btn').length && !jQuery('.next_btn').length){
console.log('condition');
}
有几个调整可以缩短这个时间:
- 在document.ready处理程序中使用别名
$
,这样就不需要到处使用jQuery
- 使用
is()
而不是hasClass()
,因为前者接受多个类 - 将中的
.prev_btn
和.next_btn
组合到单个jQuery对象中以检查length
jQuery($ => {
if (isMobile() && $('body').is('.catalog-category-view, .catalog-product-view, .wishlist-index-index') && !$('.prev_btn, .next_btn').length) {
// do something...
}
});
您可以使用以下方法优化,尽管您可以通过在变量中分配一些if条件来缩短。
var $body = jQuery("body");// get body jquery element in variable
//put OR conditions at the end as other condition can fail fast in the initial evaluation of if block
if(isMobile() && !jQuery('.prev_btn').length && !jQuery('.next_btn').length &&
($body.hasClass("catalog-category-view")
|| $body.hasClass("catalog-product-view")
|| $body.hasClass("wishlist-index-index"))){
console.log('condition');
}
或
//put AND condition as first if block
if(isMobile() && !jQuery('.prev_btn').length && !jQuery('.next_btn').length) {
//put OR condition in second if block
var $body = jQuery("body");// get body jquery element in variable
if( $body.hasClass("catalog-category-view")
|| $body.hasClass("catalog-product-view")
|| $body.hasClass("wishlist-index-index")){
console.log('condition');
}
}