[英]How can I assign the var to the innerHTML of individual buttons when the buttons are created through a for loop?
使用 Django,我的按鈕是使用 for 循環創建的,並根據模型值分配值。
根據單擊的按鈕,我想用按鈕的 innerHTML 更新“new_note_header”。
我創建了以下 JavaScript,但僅在單擊第一個按鈕時才有效。
<script>
function ProjectSelect () {
var x = document.querySelector('button').innerHTML;
document.getElementById('new_note_header').innerHTML = x;
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').onclick = ProjectSelect;
});
</script>
<div class = project_container>
{% for project in projects %}
<button class = individual_project_container>
{{ project }}
</button>
{% endfor %}
</div>
<div class = note_header_container>
<div class = new_note_header, id = new_note_header>
New Note
</div>
</div>
我將不勝感激在調整 JavaScript 方面的任何幫助,以便它適用於所有單擊的按鈕。
非常感謝
querySelector 將采用滿足選擇器的 FIRST 元素
您可以使用 querySelectorAll 並為每個事件分配一個單擊事件處理程序,但我建議使用委托:
document.addEventListener('DOMContentLoaded', function() { const nnHead = document.getElementById('new_note_header'); document.getElementById("project_container").addEventListener("click", e => { const tgt = e.target.closest("button"); if (!tgt.matches(".individual_project_container")) return; // not a button nnHead.textContent = tgt.textContent.trim(); }); });
<div class="project_container" id="project_container"> <button class="individual_project_container">Project 1</button> <button class="individual_project_container">Project 2</button> <button class="individual_project_container">Project 3</button> </div> <div class="note_header_container"> <div class="new_note_header" id="new_note_header"> New Note </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.