![](/img/trans.png)
[英]How to use a variable with class name inside a function in javascript?
[英]Django Javascript: How To Use Class Name With Template Tag Inside As Identifier in Function
我正在使用 for 循環打印出我網站上的所有帖子,每個帖子都有一個表單,允許用戶將該帖子添加到列表中。 我正在嘗試使用 ajax 來執行此操作,以免頁面刷新。 ajax function 適用於第一篇文章,但在所有其他文章中都存在問題。 我認為問題是由於每個帖子都具有相同的 class 名稱來識別它,所以這就是為什么我想在 class 名稱中使用 forloop 計數器,以便每個帖子都有一個唯一的標識符。
編輯:問題是每個表單上的按鈕應該更改 class 和文本,這在第一篇文章中有效,但在大多數文章中這不起作用。
這是一些相關的代碼:
Javascript:
#this is where i want the class to have a tag inside
$('.collection_save_form').submit(function(e){
e.preventDefault()
const url = $(this).attr('action')
const post_id = $(this).attr('name')
const collection_id = $(this).attr('id')
const text = $(`.saved_text${collection_id}`).text()
var saveElement = document.getElementById(`save_btn${collection_id}`);
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id': post_id,
'collection_id': collection_id,
},
success: function(response){
if (saveElement.classList.contains("saved")){
saveElement.classList.remove("saved")
$(`.saved_text${collection_id}`).text('Save')
} else if (!$(this).hasClass("saved")) {
saveElement.classList.add("saved")
$(`.saved_text${collection_id}`).text('Saved')
}
},
error: function(response){
console.log('error', response)
}
})
})
代碼形式為:
{% for item in posts %}
#irrelevant post data
{% for collection in collections %}
<div class="collection_save_container">
<div class="collection_save_name">{{ collection.collection_name }}</div>
{% if item.post in collection.posts.all %}
#here the class of the form should have a class that ends with something like {{ item.id }}
<form class="collection_save_form" action="{% url 'savepost' item.post.id collection.id %}" method="POST" id="{{ collection.id }}" name="{{ item.post.id }}">
{% csrf_token %}
<button type="submit" class="collection_save_btn saved" id="save_btn{{ collection.id }}"><div class="saved_text{{ collection.id }}">Saved</div></button>
</form>
{% else %}
#here the class of the form should have a class that ends with something like {{ item.id}} }}
<form class="collection_save_form" action="{% url 'savepost' item.post.id collection.id %}" method="POST" id="{{ collection.id }}" name="{{ item.post.id }}">
{% csrf_token %}
<button type="submit" class="collection_save_btn" id="save_btn{{ collection.id }}"><div class="saved_text{{ collection.id }}">Save</div></button>
</form>
{% endif %}
</div>
{% endfor %}
好的,我為任何有類似問題的人回答我自己的問題
保存元素是指 id save_btn${collection_id}
var saveElement = document.getElementById(`save_btn${collection_id}`);
但是無法確定這是來自父循環上的哪個帖子,因此需要
var saveElement = document.getElementById(`save_btn${collection_id}${post_id}`);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.