gpt4 book ai didi

javascript - 列出所有单击的图像按钮更改图像

转载 作者:行者123 更新时间:2023-12-03 06:40:54 24 4
gpt4 key购买 nike

各位,我使用django的模板语言和javascript来执行“单击图像按钮更改图像”,但是,我得到的结果是只能更改最后一个按钮。我不知道为什么代码有问题,这里是我的

indext.html

{% extends 'base.html' %}
{% load static %}
{% block title %}
Homepage - {{ block.super }}
{% endblock title %}
{% block content %}
<script>
function setColor(e, btn, color) {
var target = e.target,
count = +target.dataset.count;

target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
}

var img_array = [ src="{% static "img/published.png" %}" , src="{% static "img/draft.png" %}"];
i = 0;

{% for post in posts %}
function myFunction({{ post.model_number }}) {
i++;
document.getElementById("{{ post.model_number }}").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;

}

}
{% endfor %}

</script>

<table class="table table-bordered">
<tr>
<td>產品編號</td><td>產品名稱</td><td>建立日期</td><td>產品圖片</td><td>最後修改日期</td><td>產品說明</td><td>建立者</td><td>修改者</td><td></td>
</tr>
{% for post in posts %}
<tr>
<td> {{ post.model_number }} </td>
<td><a href="{% url 'thing_detail' slug=post.slug %}">{{ post.name }}</a></td>
<td>{{ post.created }} </td>
<td> <img src="{% if post.image %} {{ post.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}" height="100" width="100"> </td>
<td>{{ post.modified }} </td>
<td>{{ post.feature }}</td>
<td>{{ post.user }}</td>
<td>{{ post.useredit }}</td>
{% for cp in post.cataloggroup.all %}
<td> {{cp }}</td>
{% endfor %}

<td><a href="{% url 'edit_thing' slug=post.slug %}"><input class="button0 button2" type="button" id="button" value="編輯" style="color:#fffff0" onclick="setColor(event, 'button', '#101010')"; data-count="1" /><a></td>



<td><button onclick="myFunction({{ post.model_number }})"><img id="{{ post.model_number }}" src="{% static "img/published.png" %}" width="50" height="30"></button></td>


</tr>
{% endfor %}
</table>
{% include "pagination.html" with page=posts %}
{% endblock content %}

它将渲染网页

enter image description here

但是,当我点击顶部按钮时,它会改变底部按钮,我必须让每个点击的按钮都可以改变图像

enter image description here

上图我点击了顶部按钮,但更改了底部按钮的图像“已发布 ---> 草稿”

enter image description here

我必须让每个点击的按钮都可以改变它自己的图像,我该怎么做?

enter image description here

最佳答案

这是因为您有myFunction() <script> 内的定义django 中 for 循环的每次迭代都会输入到 HTML 中的标记。

这意味着该函数不断被重新定义,因此 myfunction功能将始终是最后一次迭代的功能。

如果您定义myFunction()在 django 循环之外并将型号传递给函数(如下所示),那么它应该按预期工作`

function myFunction(model_number) {
i++;
document.getElementById(model_number).src = img_array[i];
if (i == img_array.length - 1) {
i = -1;

}

}

关于javascript - 列出所有单击的图像按钮更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966405/

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