【问题标题】:Appending specific JS obj value into a modal将特定的 JS obj 值附加到模式中
【发布时间】:2019-05-01 14:29:42
【问题描述】:

我有七个课程标题,它们显示在各自的 div 中,单击任何 div 都会打开一个模式。模式被硬编码到我的 HTML 中。

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

JS sn-p:

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;

    }

模态:

<div class="modal" id="modal-id" role="dialog">
<div class="modal-title" id="exampleModalLabel"></div>

【问题讨论】:

标签: javascript jquery html object bootstrap-modal


【解决方案1】:

您可以使用简单的 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>

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2019-09-16
    • 2016-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多