我正在嘗試驗(yàn)證圖像 URL 是否存在于 javascript 中。所以我在 javascript 中添加了這段代碼,它接受 URL 并返回 http 狀態(tài)代碼。function imageExists(image_url){ var http = new XMLHttpRequest(); http.open('HEAD', image_url, false); http.send(); return http.status != 404;}在液體模板中,我想在顯示之前檢查圖像 URL 是否存在,如下所示<div class="variant-cat-attributes"> {% assign tags = product.metafields.product_meta.tag | split: "," %} {% for tag in tags %} <div class="item"> {% capture tag_slug %}{{ tag | replace: " ", "_"}}{% endcapture %} {% assign img_png = 'tag' | append: '-' | append: tag_slug | append: '.png'%} {% capture png_exists %}<script>imageExists({{ img_png }})</script>{% endcapture %} {% if png_exists%} <img src="{{ img_png | file_img_url: '32x32' }}" /> {% else %} {% assign img_jpg = 'tag' | append: '-' | append: tag_slug | append: '.jpg'%} {% capture jpg_exists %}<script>imageExists({{ img_jpg }})</script>{% endcapture %} {% if jpg_exists%} <img src="{{ img_png | file_img_url: '32x32' }}" /> {% else %} {% assign img_default = 'tag' | append: '-' | append: 'default' | append: '.png'%} <img src="{{ img_default | file_img_url: '32x32' }}" /> {% endif %} {% endif %} <p class="item-name">{{ tag | capitalize }}</p></div> {% endfor %}</div>我剛剛開(kāi)始了解液體,所以我不知道這樣是否正確。但是這段代碼發(fā)生的情況是腳本標(biāo)記被當(dāng)作字符串,并且其中的代碼沒(méi)有運(yùn)行png_exists = imageExists({{ img_png }})我該如何解決這個(gè)問(wèn)題?
將 javascript 函數(shù)輸出分配給 Liquid 變量
哆啦的時(shí)光機(jī)
2023-12-15 17:18:53