将特定的JS obj值附加到模态中

问题描述 投票:-1回答:1

我有七个课程标题,显示在他们自己的div中,点击任何一个div打开一个模态。模态被硬编码到我的HTML中。

如何将每个课程标题附加到单击的模式中?例如,通过点击Animals div,模式会弹出,并且标题“Animals”也应该出现。到目前为止,我只能展示第一个标题(Animals)并在每个模态(Animals,Capitals,Colors,etc)中显示每个标题。

JS snippet:

loadCategories(){

    let categs = _categories;

    // using templates to clone a single div based on how many Categories are present
    let $host = $("#host");
        for (var i = 0; i < categs.length; i++) {
           let $template = $("#template").clone();
           $template.find(".cat-box > .cat-title").text(categs[i].Title);
           // $(".modal-title").append(categs[i].Title) // ------- shows everything (must be due to the loop)
           $host.append($template.html());
        }

// wondering if categs[i].Title could be worked with somehow

     $(".modal-title").append(categs.Title)

    let container = document.querySelector("div#template");
        container.innerHTML = $host;

    }

Modal:

<div class="modal" id="modal-id" role="dialog">
<div class="modal-title" id="exampleModalLabel"></div>
javascript jquery html object bootstrap-modal
1个回答
0
投票

您可以使用简单的javascript从元素属性中获取所需的标题,然后将它们添加到模态中。

document.querySelectorAll('.openModal').forEach(el => {
  el.addEventListener('click', function (e) {
    e.preventDefault()
    
    const title = el.getAttribute('data-title')
    
    document.querySelector('.modal').textContent = title
  })
})
<a href="#" class="openModal" data-title="This is the new title">Click me</a>

<br />
<br />

<div class="modal">Pretend this is a modal title</div>
© www.soinside.com 2019 - 2024. All rights reserved.