简体   繁体   中英

JavaScript onerror not working in Shopify Liquid script

I've created a script that loops thru all the tags in a collection and displays a sub-category div with an image + h3 title of the sub-category/tag.

The image I upload to the assets folder in my theme and I constructed a URL of the assets folder/collection handle/tag handle + .png

The problem is that I have some tags that I don't want to display as a sub-category so I check if there is an error with loading the image and if so I hide the image plus the title/h3 tag, But the JavaScript simply does not work.

Any idea how to fix this???

{% unless current_tags %}
      {% capture col_url%}{% if collection.url.size == 0 %}/collections/all{%else%}{{collection.url}}{%endif%}{%endcapture%}
      {% if collection.all_tags.size > 0 %}
        <div class="grid text-center">
          {% for tag in collection.all_tags %}
              {% capture file_name %}{{ collection.handle }}-{{ tag | handle }}.png{% endcapture %}
              {% capture alt_attr %}{{ collection.title | escape }}-{{tag | handle}}{% endcapture %}
              <div class="grid-item large--one-eighth medium--one-third" id="{{ collection.handle }}-{{ tag | handle }}-div">
                <a href="{{col_url}}/{{tag | handle}}">
                  <img src="{{ file_name | asset_url }}" alt="{{ alt_attr }}" id="{{ collection.handle }}-{{ tag | handle }}-img">
                </a>
                  <h3 id="{{ collection.handle }}-{{ tag | handle }}-h3">{{ tag | link_to_tag: tag }}</h3>
              </div>
          <script>
            document.getElementById("{{ collection.handle }}-{{ tag | handle }}-img").onerror = function(){
                document.getElementById("{{ collection.handle }}-{{ tag | handle }}-h3").style.display = "none";
                document.getElementById("{{ collection.handle }}-{{ tag | handle }}-img").style.display = "none";
            }                 
          </script>
          {% endfor %}
        </div>
      {% endif %}
{% endunless %}

I fixed it by writing the JavaScript in the image onerror attribute, here's my code:

<img src="{{ file_name | asset_url }}" alt="{{ alt_attr }}" id="{{ collection.handle }}-{{ tag | handle }}-img" onerror="this.onerror = null;this.parentElement.parentElement.style.display = 'none'">

But I'll still like to figure out what the issue was in first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM