gpt4 book ai didi

javascript - 使用 jQuery 在 Jinja2 循环内提供 onclick 事件

转载 作者:行者123 更新时间:2023-11-28 05:18:14 25 4
gpt4 key购买 nike

我正在使用 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>

最佳答案

您确实不需要附加 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>

此外,我建议您避免给出固定的 id喜欢 <div hidden class="col-md-9" id="details">每当你在循环内生成 HTML 时。 id应该是唯一的,并且不应在您的 HTML 页面中重复

关于javascript - 使用 jQuery 在 Jinja2 循环内提供 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40792796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com