[英]jQuery .on() not triggering the desired function
我已经编写了一些代码来过滤 collections。 但是当输入点击时它不会触发(用console.log
检查)
这是我的代码:
{% for collection in collections %}
$('#collection-{{ collection.title | replace: " ", "" }}').on('click', function(event){
showCollection('{{ collection.title | replace: " ", "" }}');
});
{% endfor %}
这是 HTML:
{% for collection in collections %}
<li>
<input type="radio" name="categoryCollection" id="collection-{{ collection.title | replace: " ", "" }}" value="{{ collection.title }}">
<label for="collection-{{ collection.title | replace: " ", "" }}">{{ collection.title }}</label>
</li>
{% endfor %}
我错过了什么? 谢谢!
编辑:我使用的逻辑是流动的,因为我正在创建一个 Shopify 主题。 此外,在控制台中一切正常。 我将在这里添加渲染的 HTML:
<ul>
<li>
<input type="radio" name="categoryCollection" id="collection-Jackets" value="Jackets">
<label for="collection-Jackets">Jackets</label>
</li>
<li>
<input type="radio" name="categoryCollection" id="collection-LuxuryTracksuits" value="Luxury Tracksuits">
<label for="collection-LuxuryTracksuits">Luxury Tracksuits</label>
</li>
<li>
<input type="radio" name="categoryCollection" id="collection-Masks" value="Masks">
<label for="collection-Masks">Masks</label>
</li>
<li>
<input type="radio" name="categoryCollection" id="collection-T-Shirts" value="T-Shirts">
<label for="collection-T-Shirts">T-Shirts</label>
</li>
<li>
<input type="radio" name="categoryCollection" id="collection-Trousers" value="Trousers">
<label for="collection-Trousers">Trousers</label>
</li>
</ul>
EDIT2:我创建了一个工作小提琴,它只有一个问题:它有效。 在这里你可以看到
这可以变得更加通用,而无需循环来为每个无线电 id 创建事件侦听器。
请注意添加到每个内容元素的 class 以使隐藏它们也通用
只需从发生事件的收音机中获取值即可过滤掉您需要显示的内容
$('.filter:radio[name="collection"]').change(function(){ const content_id = 'collection_' + this.value.toLowerCase(); $('.collection_content').hide().filter('#' + content_id).show(); });
.collection_content{display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="filter"> <ul> <li> <input type="radio" id="Jackets" value="Jackets" name="collection"> <label for="jackets" >Jackets</label> </li> <li> <input type="radio" id="Shirts" value="Shirts" name="collection"> <label for="Shirts">shirts</label> </li> <li> <input type="radio" id="Masks" value="Masks" name="collection"> <label for="Masks">Masks</label> </li> </ul> </div> <div class="collection-wrap"> <div id="collection_jackets" class="collection_content">JacketsJacketsJackets</div> <div id="collection_shirts" class="collection_content">ShirtsShirtsShirts</div> <div id="collection_masks" class="collection_content">MaksMaksMaks</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.