简体   繁体   English

当通过 for 循环创建按钮时,如何将 var 分配给各个按钮的 innerHTML?

[英]How can I assign the var to the innerHTML of individual buttons when the buttons are created through a for loop?

Using Django, my buttons are created using a for loop and assigned values based on model values.使用 Django,我的按钮是使用 for 循环创建的,并根据模型值分配值。

Based on which button is click, I want to update the "new_note_header" with the innerHTML of the button.根据单击的按钮,我想用按钮的 innerHTML 更新“new_note_header”。

I have created the following JavaScript, which works but only when the first button clicked.我创建了以下 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>

I would be grateful for any help in adapting the JavaScript so it works for all buttons clicked.我将不胜感激在调整 JavaScript 方面的任何帮助,以便它适用于所有单击的按钮。

Many thanks非常感谢

querySelector will take the FIRST element that satisfies the selector querySelector 将采用满足选择器的 FIRST 元素

You could use querySelectorAll and assign a click event handler to each, but I recommend using delegation:您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM