在JavaScript模板字面量字符串中使用if/三元运算符的正确语法
模板字面量条件判断实现方案
模板字面量的${}占位符内支持写入任意合法JS表达式,三元运算符可直接放在占位符内实现条件判断,针对你提到的两个需求实现方式如下:
- 图片存在性校验:搭配可选链
?.规避product.images未定义时报错,无首图时可替换为项目预设的占位图地址,避免页面出现裂图。 - 划线价条件渲染:仅当商品对比价(原价)大于实际售价时才显示划线价标签,不符合条件时返回空字符串即可隐藏该元素。
修改后的完整代码如下:
if(products.length > 0) { products.forEach(function(product, index) { const productRow = ` <div class="col-md-3 col-lg-3 col-sm-6 col-xs-6 init"> <div class="product-item mb-0 wow fadeIn" data-wow-offset="10" data-wow-duration="1s" data-wow-delay="500ms"> <div class="product-thumb"> <div class="reveal img-fluid"> <a href="${product.url}"><img class="img-fluid" src="${product.images?.[0] ? product.images[0] : '你的项目占位图地址'}" alt="${product.title}" /></a> </div> </div> <div class="product-content py-2"> <h3><a href="${product.url}">${product.title}</a></h3> <p class="home-price-inline mb-0"> <span class="js-price" data-default-price="{{ current_variant.price | money }}">${Currency.formatMoney(product.price_min)}</span> ${product.compare_at_price > product.price_min ? `<s class="ml-0">${Currency.formatMoney(product.compare_at_price)}</s>` : ''} </p> </div> </div> </div>`; productRecomendationBody.insertAdjacentHTML('afterbegin', productRow); }); }
如果后续需要实现更复杂的多条件判断,也可以把逻辑抽成单独的工具函数,直接在${}内调用函数返回结果即可,代码可读性会更高。
内容的提问来源于stack exchange,提问作者Whiley Mai
相关产品推荐
相关产品推荐

