Javascript 带开关的重因子分解

Javascript 带开关的重因子分解,javascript,Javascript,所以,我有下面的jQuery代码,它针对一些DOM元素,我想把代码改成一个switch语句,但我找不到一个方法,有人有什么想法或者可以给我一个模型来做吗 if ($('.similar-products')) { $('.similarproducts').append(iframe_html); } if ($('.partial--product')){ $('.partial--product

所以,我有下面的jQuery代码,它针对一些DOM元素,我想把代码改成一个switch语句,但我找不到一个方法,有人有什么想法或者可以给我一个模型来做吗

if ($('.similar-products')) {                                       
    $('.similarproducts').append(iframe_html);
} 

if ($('.partial--product')){
    $('.partial--product').append(iframe_html);
}

if ($('.product-page')){
    $('div.product-page').append(iframe_html);
}

if($('#section-product-page')){
   $('#section-product-page').append(iframe_html);
}
//needs fix
if($('.swatch-product-id-*')){
   $('.swatch-product-id-*').append(iframe_html);
}

if($('.product__tabs')){
   $('.product__tabs').append(iframe_html);
}
if($('.main-content-wrapper')){
   $('.main-content-wrapper').append(iframe_html);
}

if($('#shopify-section-product-description-bottom-template')){
   $('#shopify-section-product-description-bottom-template').append(iframe_html);
}
if($('.product-details-inline')){
   $('.product-details-inline').append(iframe_html);
}

if($('.social-footer')){
   $('.social-footer').prepend(iframe_html);
}
if($('.section-related-products')){
   $('.section-related-products').append(iframe_html);
}

if($('.product-details')){
   $('.product-details').append(iframe_html);
}

在这种情况下,它甚至比在数组上迭代的循环更容易:

let selectors = [
    '.similar-products',
    '.partial--product',
    ... ]


selectors.forEach(x => {
    if($(x).length > 0) {
        $(x).append(iframe_html)
    } 
})

像这样的事情可能更容易

var elements = [
    '.similar-products',
    '.partial--product',
    '.product-page',
    '#section-product-page',
    '.swatch-product-id-*',
    '.product__tabs',
    '.main-content-wrapper',
    '#shopify-section-product-description-bottom-template',
    '.product-details-inline',
    '.social-footer'
];

elements.forEach(element => {
    if($(element)){
        $(element).append(iframe_html);
    }
});

从我可以看出,在每个
if
语句中,您都在做同样的事情。使用jquery选择器创建字符串数组,并对其运行相同的函数。Switch语句“可能”比加载
if
语句要好,但这种方式使添加或删除检查和追加变得更容易

为什么要将其更改为switch语句?另外,您确实意识到,当jQuery从选择器返回一个对象时,您的
if
语句将始终是真实的?我想将它们更改为开关状态,以便更快地进行优化,有人提出了建议,我喜欢idea,但我不知道如何才能做到这一点,或者它是否会工作,我只想重新考虑代码a
开关
与控制流无关。不要用它。