索引.html
<script>
function hide_image() {
var show = document.getElementById("showimage");
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
}
</script>
{% 塊內容 %}
<center>
{% for post in post_list %}
{{post.user.username}}
<br>
{{post.date_time}}
<br>
{{post.content}}
<br>
<button id="hide_image" onclick="hide_image()">Hide</button>
{% for image in post.postimage_set.all %}
<img id="showimage" src="{{image.images.url}}" alt="postimage" style="width: 300px;">
{% endfor %}
<br>
{% for file in post.postfile_set.all %}
<a href="{{file.files.url}}">{{file.files}}</a>
{% endfor %}
<br>
<a href="{% url 'comment' post.id %}">Comment</a>
<hr>
{% endfor %}
</center>
{% endblock %}
我試圖在單擊隱藏按鈕時隱藏影像,但是當我單擊任何影像元素的隱藏按鈕時,只有第一個元素的影像被隱藏。為什么會這樣?誰能解釋一下?
uj5u.com熱心網友回復:
在您的塊內容中,在所有帶有帖子 ID 的影像中使用不同的類名。還將帖子 id 傳遞給hide_image function
以捕獲相關影像:
<button id="hide_image" onclick="hide_image({{post.id}})">Hide</button>
<img class="showimage-{{post.id}}" src="{{image.images.url}}" alt="postimage" style="width: 300px;">
然后在您的腳本中,選擇所有相關影像并對單擊的按鈕進行操作:
<script>
function hide_image(id) {
var shows = document.querySelectorAll(`.showimage-${id}`);
shows.forEach(show => {
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
})
}
</script>
uj5u.com熱心網友回復:
在 hide_image 函式中使用document.querySelectorAll()
而不是document.getElementById()
使用 for 回圈或forEach
實作 if 陳述句
uj5u.com熱心網友回復:
在 for 回圈中定義一個 int 并將其遞增一,然后將其傳遞給影像 id 和 hide_image 函式以允許該函式正確識別所選影像,例如
<button id="hide_image" onclick="hide_image({{i}})">Hide</button>
<img id="showimage{{i}}" src="{{image.images.url}}" alt="postimage" style="width: 300px;">
<script>
function hide_image(var x) {
var show = document.getElementById("showimage" x);
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495675.html
標籤:javascript html dom 前端
上一篇:如何在dom中設定值?