简体   繁体   English

显示引导模式时,function 运行多次。 香草 js

[英]a function runs multiple times when showing a bootstrap modal. vanilla js

I have a button that shows a bootstrap modal, it has an onclick attribute set to a function,我有一个显示bootstrap模式的button ,它的onclick属性设置为 function,

The button:按钮:

<span style="color:blue;margin-left: 2rem;" data-id="{{student.id}}" id="{{student.id}}"
   type="button" data-bs-toggle="modal" data-bs-target="#grade-modal" 
   onClick="getEnrolledSubjects(this.getAttribute('data-id'))">
    <i class="fas fa-plus"></i>
</span>

My javascript function:我的 javascript function:

function getEnrolledSubjects(id){
    var modal = document.getElementById('grade-modal')
    modal.addEventListener('shown.bs.modal', function(){
        console.log(id)
    }
}

at first, it looks fine because it will only log the id once, but when I close the modal and open it again, it will log 2 times, then 3 times, and so on... it goes incrementally.起初,它看起来不错,因为它只会记录一次id ,但是当我关闭模式并再次打开它时,它会记录 2 次,然后 3 次,依此类推......它会逐渐增加。 how can i fix this?我怎样才能解决这个问题?

as Bootstrap Modal documentation作为Bootstrap Modal 文档

You can Use event.relatedTarget :您可以使用event.relatedTarget

<span style="color:blue;margin-left: 2rem;" data-id="{{student.id}}" id="{{student.id}}" type="button" data-bs-toggle="modal" data-bs-target="#grade-modal">
    <i class="fas fa-plus"></i>
</span>

without onClick event没有onClick事件

const modal = document.getElementById('grade-modal')
modal.addEventListener('shown.bs.modal', function(event){
    const button = event.relatedTarget
    const id = button.getAttribute('data-id');
    console.log(id)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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