javascript - 我怎样才能以聪明的方式重构它

标签 javascript jquery html

所以基本上我有一个寻找 div 并向其附加 iframe 的代码,但我仅将它们作为 if 语句的开始,知道如何重构它们,尝试了一些 else-if 但他们没有'不工作。代码如下所示:

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);
}

最佳答案

我猜你在这里使用的是 jQuery。如果是这样的话,有 if block 是没有意义的。因为 jQuery 会查找匹配的选择器并执行函数中指定的任务。如果没有找到给定选择器的元素,则例程将被忽略,不会出现错误。所以,有类似的东西

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

没什么不同
$('.similarproducts').append(iframe_html);

此外,考虑对选择器进行分组,如果 <iframe>您附加的内容对于所有人来说都是相同的。所以它会是这样的

$('.similarproducts, .partial--product' /* Rest of the selectors */).append(iframe_html);

关于javascript - 我怎样才能以聪明的方式重构它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893534/

相关文章:

html - 在 CSS 中 float - 向右浮动时在顶部留下的间隙/空间?

javascript - 我有 2 个 UI 选项卡。我需要通过单击该选项卡外的按钮来激活一个特定选项卡

javascript - 区分 AJAX 调用/浏览器请求

javascript - 尝试使用 ajax 加载网页的一部分,而不阻塞整个页面。如何?

javascript - ReactJS - 外部 JS 函数 "is not a function"

c# - 文本框中文本的消失和重新出现

javascript - 动态创建的 JQUERY 按钮默认为最后创建的元素

javascript - AGGrid 与 react ,调用 this.gridApi.sizeColumnsToFit();不适合列

javascript - 如何在功能之间切换

html - 如何正确清除这些 float 的 div?