[英]How can I refactor this in a smart way
所以基本上,我有一個代碼來查找div並將iframe附加到它們上,但是我只是以if語句作為開始,讓我知道如何重構它們,嘗試了一些其他方法-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
塊是毫無意義的。 因為jQuery查找匹配的選擇器並執行功能中指定的任務。 如果找不到給定選擇器的元素,則例程將被忽略而不會出錯。 所以,像
if ($('.similar-products')) {
$('.similarproducts').append(iframe_html);
}
沒什么不同
$('.similarproducts').append(iframe_html);
此外,如果要附加的<iframe>
對於所有對象都相同,請考慮對選擇器進行分組。 所以這就像
$('.similarproducts, .partial--product' /* Rest of the selectors */).append(iframe_html);
您可以使用Switch case語句代替if and else,因為在if else的情況下,服務器將檢查每個if and else條件,但是在switch的情況下,它將直接跳過相關的case塊。 因此可以最大化性能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.