<div class="trendingItem" data-id="${item.id}" data-type="${item.media_type}">
<a href="#" id="viewItem" class="viewItem">
<img src='https://image.tmdb.org/t/p/original/${item.backdrop_path}' loading="lazy" alt="movie poster"/>
</a>
<h4>${item.title ? item.title : item.name}</h4>
</div>
所以這是我的代碼,我試圖做一個三元陳述句,基本上說如果沒有影像,然后插入一條訊息說沒有找到影像,但我不知道該怎么做。
更新:
這是我嘗試過的,但到目前為止它不起作用。
<div class="trendingItem" data-id="${item.id}" data-type="${item.media_type}">
<a href="#" id="viewItem" class="viewItem">
<img src='https://image.tmdb.org/t/p/original/${item.backdrop_path} ? ${item.backdrop_path} : <h4>No Image Found</h4>' loading="lazy" alt="movie poster"/>
</a>
<h4>${item.title ? item.title : item.name}</h4>
</div>
uj5u.com熱心網友回復:
假設您的 HTML 在 JavaScript 模板字面量中,并且您只想在為真時顯示影像item.backdrop_path,您需要將您的三元陳述句評估為整體的<img>or 或<h4>元素。
const html = `
<div data-id="${item.id}" data-type="${item.media_type}">
<a href="#" id="viewItem" >
${item.backdrop_path
? `<img src="https://image.tmdb.org/t/p/original/${item.backdrop_path}" loading="lazy" alt="我的電視/電影應用程式中的某些節目/電影沒有海報。如果找不到影像,如何撰寫顯示訊息的三元陳述句?"/>`
: "<h4>No Image Found</h4>"
}
</a>
<h4>${item.title ? item.title : item.name}</h4>
</div>
`.trim();
我強烈建議不要創建 HTML 字串。相反,使用 DOM 方法來創建實際元素
const createElement = (tag, attributes, ...children) => {
const el = document.createElement(tag);
Object.fromEntries(attributes).forEach(([attr, val]) => {
el.setAttribute(attr, val);
});
el.append(...children);
return el;
};
const div = createElement(
"div",
{ class: "trendingItem", "data-id": item.id, "data-type": item.media_type },
createElement(
"a",
{ href: "#", id: "viewItem", class: "viewItem" },
item.backdrop_path
? createElement("img", {
src: `https://image.tmdb.org/t/p/original/${item.backdrop_path}`,
loading: "lazy",
alt: "movie poster",
})
: createElement("h4", {}, "No Image Found"),
createElement("h4", {}, item.title ?? item.name)
)
);
uj5u.com熱心網友回復:
在你的 div 之后添加這個
<script>
var req = new XMLHttpRequest();
req.open("GET",
'https://image.tmdb.org/t/p/original/' item.backdrop_path, false);
req.send();
if(req.statusCode != 200) {
var elem = document.getElementById("viewItem");
elem.innerHTML = "<h4>No Image Found</h4>";
}
</script>
含義:如果有圖片,嘗試獲取圖片,如果沒有,將a的內部html改為not found h4
PS我沒有整個頁面,所以我無法測驗我的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486285.html
標籤:javascript html api
上一篇:使用來自單獨函式的異步代碼時如何處理JavaScript閉包
下一篇:單擊按鈕時試圖顯示搜索欄?
