使用Shuffle.JS从AJAX加载JSON生成Bootstrap卡片:移除无图片项的img标签
Solution for Conditional Image Tag in Bootstrap Cards
Got it, let's fix that annoying missing image placeholder issue! The core fix here is to conditionally render the <img> tag only when the blog_image field exists and isn't empty. Here's the adjusted version of your function:
function getMarkupFromData(dataForSingleItem) { const { blog_title: blogtitle, blog_text: blogtext, blog_image: blogimage, blog_url: blogbutton, blog_tags: categories, date: blogdate } = dataForSingleItem; // Start building the markup array const markupParts = [ '<div class="js-item mb-4" style="width: 22rem;" data-groups=' + categories + ' data-date-created= '+ blogdate +' data-title="'+ blogtitle + '">', '<div class="card w-100">' ]; // Only add the img tag if blogimage exists and isn't empty if (blogimage && blogimage.trim() !== '') { markupParts.push('<img class="card-img-top" src="' + blogimage +'">'); } // Add the rest of the card content markupParts.push( '<div class="card-body">', '<div class=js-item__details>', '<h3 class="card-title bold">' + blogtitle + '</h3>', '</div>', '<p class="card-text">' + blogtext + categories + '</p>', '<a href="' + blogbutton + '" class="btn btn-primary">Read More</a>', '</div>', '</div>', '</div>' ); return markupParts.join(''); }
What changed?
- Cleaner Variable Setup: I used object destructuring at the start to make variable assignments neater (optional, but it makes the code easier to scan).
- Conditional Image Logic: Instead of hardcoding the
<img>tag in the initial array, we check ifblogimageis truthy and not just whitespace. If it passes both checks, we add the image tag to our markup. - Modular Markup Building: Splitting the card into parts lets us insert conditional elements without messy, hard-to-read string concatenation.
If you want to make the code even cleaner and reduce the risk of syntax errors, consider using template literals (backticks) for the markup:
function getMarkupFromData(dataForSingleItem) { const { blog_title: blogtitle, blog_text: blogtext, blog_image: blogimage, blog_url: blogbutton, blog_tags: categories, date: blogdate } = dataForSingleItem; let imageMarkup = ''; if (blogimage && blogimage.trim() !== '') { imageMarkup = `<img class="card-img-top" src="${blogimage}">`; } return ` <div class="js-item mb-4" style="width: 22rem;" data-groups=${categories} data-date-created=${blogdate} data-title="${blogtitle}"> <div class="card w-100"> ${imageMarkup} <div class="card-body"> <div class=js-item__details> <h3 class="card-title bold">${blogtitle}</h3> </div> <p class="card-text">${blogtext}${categories}</p> <a href="${blogbutton}" class="btn btn-primary">Read More</a> </div> </div> </div> `.trim(); }
Template literals make the markup structure visually clear and eliminate the need for repeated + concatenation.
内容的提问来源于stack exchange,提问作者Alexis Drakopoulos
相关产品推荐
相关产品推荐

