我正在使用Python / Flask / Jinja2
在for循环中,我想点击{{place.place_photo}}来切换细节。我让它工作,除了它切换所有项目,而不是一次只切换一个。
HTML:
{% if places %}
<div class="col-md-12 company_content_img_all">
{% for place in places %}
<div class="row col-md-3" id="place_pic">
<div class="company_img_block company_btn1">
<img src="{{ place.place_photo }}" class="popos_img" type="button" id="button_{{ place.place_photo }}">
<div class="company_img_desc">{{ place.title }}</div>
</div>
</div>
<div hidden class="col-md-9" id="details">
<div id="details_{{ place.place_photo }}">
<p>
<b>Description:</b> {{ place.description }}<br/>
<b>Address:</b> {{ place.address }}<br/>
<b>Neighborhood:</b> {{ place.neighborhood }}<br/>
</p>
</div>
</div>
{% endfor %}
</div>
{% endif %}
jQuery的:
<script>
$(document).ready(function() {
$('.button').each(function(){
$(this).click(function(){
$('#details_'+$(this).attr('place_photo')).toggle();
});
});
});
</script>
答案 0 :(得分:0)
您真的不需要在循环中附加click
事件处理程序。您可以通过以下方式实现它:
<script>
$(document).ready(function() {
//attach the click event to all <img> tag having class 'popos_img'
//here no need of any for loop
$('.popos_img').click(function(){
var currentId = $(this).attr("id");
var variablePart = currentId.replace("button_",""); //grab the only variable part so that we can formulate the associated id of div
$('#details_'+variablePart).toggle(); //toggle the associated div
});
});
</script>
另外,我建议您在循环中生成HTML时避免使用id
这样的固定<div hidden class="col-md-9" id="details">
。 id
应该是唯一的,并且不应该在HTML页面中重复
答案 1 :(得分:0)
您不需要.each
为每个button
分配点击事件。此外,我无法识别代码中的任何.button
元素。
假设您要将点击事件附加到img
类popos_img
,您可以直接执行以下操作。我建议你的设计也要做一些改动,以使其更简单。以下是您的更新设计:
{% for place in places %}
<div class="parent"> <!--Wrap this in a parent div-->
<div class="row col-md-3"> <!--remove id from here as it creates duplicates inside for loop-->
<!--or create an unique one-->
<div class="company_img_block company_btn1">
<img src="{{ place.place_photo }}" class="popos_img" type="button" id="button_{{ place.place_photo }}">
<div class="company_img_desc">{{ place.title }}</div>
</div>
</div>
<div class="toggled col-md-9 hidden"><!--remove id from here as it creates duplicates inside for loop-->
<!--or create an unique one-->
<div id="details_{{ place.place_photo }}">
<p>
<b>Description:</b> {{ place.description }}<br/>
<b>Address:</b> {{ place.address }}<br/>
<b>Neighborhood:</b> {{ place.neighborhood }}<br/>
</p>
</div>
</div>
</div>
{% endfor %}
您的按钮点击事件将是:
$(document).ready(function() {
$('.button').on('click',function(){
$(this).closest('div.parent').find('div.toggled').toggleClass('hidden');
});
});
另请注意,id's
中的html
应该是唯一的,因此不会在for loop
内生成静态ID