我正在嘗試發送我們選擇在表單操作中編輯的物件的 ID。
let edit_buttons = document.querySelectorAll(".edit-modal");
for(var i = 0; i < edit_buttons.length; i ) {
edit_buttons[i].addEventListener("click", function(e) {
console.log(`${this.getAttribute("data-id")}`)
console.log(`{% url 'users:edit' pk=1 %}`)
document.querySelector("form").setAttribute("action", `{% url 'internal-users:edit-product' pk=${this.getAttribute("data-id")} %}`);
})
}
<tr>
<td class="border-0 size-13 text-gray-dark">
<button class="btn btn-gray text-gray size-13 edit-modal" data-id="1" data-toggle="modal" data-target="#editModal">Edit</button>
</td>
</tr>
<tr>
<td class="border-0 size-13 text-gray-dark">
<button class="btn btn-gray text-gray size-13 edit-modal" data-id="2" data-toggle="modal" data-target="#editModal">Edit</button>
</td>
</tr>
{% endfor %}
<form method="POST" action="">
{% csrf_token %}
<input type="hidden" id="object_id">
</form>
因此,如果我們選擇第一個條目進行編輯,我希望表單的操作為 /users/1/edit/
如果我嘗試使用 javascript 添加,我會收到以下錯誤
Could not parse the remainder: '${this.getAttribute("data-id")}' from '${this.getAttribute("data-id")}'
如果有人可以幫助我,我會很高興,在此先感謝!
uj5u.com熱心網友回復:
代表
document.querySelector("#myTable tbody").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("edit-modal")) {
document.getElementById("postForm").action = `someurl?id=${tgt.dataset.id}`;
console.log(document.getElementById("postForm").action)
}
})
<table id="myTable">
<tbody>
<tr>
<td class="border-0 size-13 text-gray-dark">
<button class="btn btn-gray text-gray size-13 edit-modal" data-id="1" data-toggle="modal" data-target="#editModal">Edit</button>
</td>
</tr>
<tr>
<td class="border-0 size-13 text-gray-dark">
<button class="btn btn-gray text-gray size-13 edit-modal" data-id="2" data-toggle="modal" data-target="#editModal">Edit</button>
</td>
</tr>
</tbody>
</table>
<form method="POST" id="postForm" action="">
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337562.html
標籤:javascript html 姜戈
