将动态数据从数组对象插入到引导模式中 - vanilla javascript

Posted

技术标签:

【中文标题】将动态数据从数组对象插入到引导模式中 - vanilla javascript【英文标题】:Insert dynamic data into bootstrap modal from array object - vanilla javascript 【发布时间】:2021-12-31 07:13:45 【问题描述】:

您好,我正在尝试将数据动态输入到我的模式中,但无法获取正确的数据。 我将简要解释我的项目 - 我有 2 个下拉菜单。 这些菜单由从 2 个数组动态输入的选项填充。 当您从选择菜单中选择一个或两个选项时,将创建一个新数组。 然后过滤新数组并仅将匹配结果作为按钮返回。 按钮打开一个模式,我想在其中显示 gif。 现在这是我卡住的地方,我让数据出现在模式中,但它不是特定于其按钮的数据,而是显示新数组中的第一个 gif。 数组对象看起来像这样 bodyPart:'颈部',设备:'体重',gifUrl:'http://d205bpvrqc9yn1.cloudfront.net/1403.gif',id:'1403',名称:'颈部侧伸展',...

工作代码sn-p https://jsfiddle.net/q08dw5mn/ html
<div class="row-md-6 offset-md-2">
  <div class="col-sm-10" style="border:1px solid blue">
    Logo goes here 

    <div class="row">
      <div class="col-8 col-sm-6" style="border:1px solid red">
        <div id="exercises" class="bg-primary align-items-center dropdown"></div> <!--------Dropdown Buttons-->
      </div>
      <div class="col-4 col-sm-6 resultdiv" style="border:1px solid red">
        <div id="data"></div> <!--Result Data-->
      </div>
    </div>
  </div>
</div>

<!--! Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div id="modalImg" class="modalBody">
        <!-- MODAL IMAGE GOES HERE -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

javascript

const dataDiv = document.getElementById("data")
const apiURL = 'https://exercisedb.p.rapidapi.com/exercises/bodyPart/%7Bchest%7D'

let mainList = []
let bodypartsList = []
let equipmentList = []


async function getApiURL(endpoint, value) 
    const response = await fetch(`https://exercisedb.p.rapidapi.com/exercises/$endpoint/$value`, 
        "method": "GET",
        "headers": 
            "x-rapidapi-host": "exercisedb.p.rapidapi.com",
            "x-rapidapi-key": "360a6abca3mshcfce9cbd521f228p1e181djsn14d1d0e4c955"
        
    )
    const data = await response.json();
    if (endpoint == "bodypart") 
        bodypartsList = data
     else 
        equipmentList = data
    
    mergeLists()


function mergeLists() 
    mainList = bodypartsList.concat(equipmentList);
    displayData(mainList)



//bodypart code
const bodyparts = ["Body Parts", "back", "cardio", "chest", "lower arms", "lower legs", "neck", "shoulders", "upper arms", "upper legs", "waist"]
const equipment = ["Equipment", "assisted", "band", "barbell", "body weight", "cable", "dumbbell", "kettlebell", "leverage machine", "medicine ball", "resistance band", "roller", "rope", "smith machine", "trap bar", "weighted"]


const exercises = document.getElementById("exercises");


window.addEventListener("load", function () 
    createDropdown("bodypart", bodyparts);
)
window.addEventListener("load", function () 
    createDropdown("equipment", equipment);
)


function createDropdown(name, items) 
    const select = document.createElement("select"); //---create the select element
    select.className = "selectMenu"
    select.name = name
    select.id = name
    for (let i = 0; i < items.length; i++)  //---as long as 'i' is less than the number of items increase by 1
        const item = items[i]; //---declaring 'i' as items
        const option = document.createElement("option"); //---create options for select
        option.setAttribute("value", item); //---places item value into options
        option.innerHTML = item; //---change content of options to items
        select.appendChild(option); //---append options to select

    
    exercises.appendChild(select); //---append select to exercises div


    select.addEventListener("change", function () 
        const item = select.value;
        dataDiv.innerHTML = ''; //<------Clears previous results from page
        getApiURL(name, item);
    )



function displayData(data) 
    let d1 = document.getElementById("equipment")
    let d2 = document.getElementById("bodypart")
    let result = data;
    if (d1.selectedIndex > 0) 
    const selected = d1.value;
    result = result.filter((equipment) => equipment.includes(selected));
    

    if (d2.selectedIndex > 0) 
    const selected = d2.value;
    result = result.filter((bodyPart) => bodyPart.includes(selected));
    

    //Filter based on value
    // const result = data.filter(word => 
    //     let check = word.name.indexOf(d1.value)
    //     let check2 = word.name.indexOf(d2.value)
    //     if (check !== -1 || check2 !== -1) 
    //         return word
    //      else 
    //         return 
            
    //     
    // );
    const unique = [];
    const uniqueImg = [];

    //Filter our duplicates
    result.map(x => unique.filter(a => a.id == x.id).length > 0 ? null : unique.push(x));
    console.log(unique);

    result.map(x => uniqueImg.filter(a => a.id == x.id).length > 0 ? null : uniqueImg.push(x));
    console.log(uniqueImg);

    unique.forEach(element => 
        const div = document.createElement("div");
        const button = document.createElement("button");
        button.ID = "myBtn"
        // const img = document.createElement("img");
        
        // img.className = "appGifs"
        button.innerHTML = element.name
        // img.src = element.gifUrl
        div.appendChild(button)
        // modalImg.appendChild(img)
        div.className = "card"
        dataDiv.appendChild(div)

        button.className = "dButtons";
        button.setAttribute('data-toggle', 'modal');
        button.setAttribute('data-target', '#exampleModalCenter');
        button.setAttribute('type', 'button');
    );
    
    uniqueImg.forEach(element => 
        const modalImg = document.getElementById("modalImg")
        const img = document.createElement("img");
        img.className = "appGifs"
        img.src = element.gifUrl
        modalImg.innerHTML = (img.gifURL)
        modalImg.appendChild(img)
    );

这是我的最后一块拼图,已经在这里卡了几天,如果有人可以帮助我通过这个,我会很高兴 谢谢

【问题讨论】:

【参考方案1】:

您没有将对象的数据传递给模式。我已经对您的代码进行了更改,现在我在单击按钮时传递数据。

const dataDiv = document.getElementById("data")
const apiURL = 'https://exercisedb.p.rapidapi.com/exercises/bodyPart/%7Bchest%7D'

let mainList = []
let bodypartsList = []
let equipmentList = []


async function getApiURL(endpoint, value) 
    const response = await fetch(`https://exercisedb.p.rapidapi.com/exercises/$endpoint/$value`, 
        "method": "GET",
        "headers": 
            "x-rapidapi-host": "exercisedb.p.rapidapi.com",
            "x-rapidapi-key": "360a6abca3mshcfce9cbd521f228p1e181djsn14d1d0e4c955"
        
    )
    const data = await response.json();
    if (endpoint == "bodypart") 
        bodypartsList = data
     else 
        equipmentList = data
    
    mergeLists()


function mergeLists() 
    mainList = bodypartsList.concat(equipmentList);
    displayData(mainList)



//bodypart code
const bodyparts = ["Body Parts", "back", "cardio", "chest", "lower arms", "lower legs", "neck", "shoulders", "upper arms", "upper legs", "waist"]
const equipment = ["Equipment", "assisted", "band", "barbell", "body weight", "cable", "dumbbell", "kettlebell", "leverage machine", "medicine ball", "resistance band", "roller", "rope", "smith machine", "trap bar", "weighted"]


const exercises = document.getElementById("exercises");


window.addEventListener("load", function () 
    createDropdown("bodypart", bodyparts);
)
window.addEventListener("load", function () 
    createDropdown("equipment", equipment);
)


function createDropdown(name, items) 
    const select = document.createElement("select"); //---create the select element
    select.className = "selectMenu"
    select.name = name
    select.id = name
    for (let i = 0; i < items.length; i++)  //---as long as 'i' is less than the number of items increase by 1
        const item = items[i]; //---declaring 'i' as items
        const option = document.createElement("option"); //---create options for select
        option.setAttribute("value", item); //---places item value into options
        option.innerHTML = item; //---change content of options to items
        select.appendChild(option); //---append options to select

    
    exercises.appendChild(select); //---append select to exercises div


    select.addEventListener("change", function () 
        const item = select.value;
        dataDiv.innerHTML = ''; //<------Clears previous results from page
        getApiURL(name, item);
    )



function displayData(data) 
    let d1 = document.getElementById("equipment")
    let d2 = document.getElementById("bodypart")
    let result = data;
    if (d1.selectedIndex > 0) 
    const selected = d1.value;
    result = result.filter((equipment) => equipment.includes(selected));
    

    if (d2.selectedIndex > 0) 
    const selected = d2.value;
    result = result.filter((bodyPart) => bodyPart.includes(selected));
    

    const unique = [];

    //Filter our duplicates
    result.map(x => unique.filter(a => a.id == x.id).length > 0 ? null : unique.push(x));
    console.log(unique);

    unique.forEach(element => 
        const div = document.createElement("div");
        const button = document.createElement("button");
        button.ID = "myBtn"
        // const img = document.createElement("img");
        
        // img.className = "appGifs"
        button.innerHTML = element.name
        // img.src = element.gifUrl
        div.appendChild(button)
        // modalImg.appendChild(img)
        div.className = "card"
        dataDiv.appendChild(div)

        button.className = "dButtons";

        button.setAttribute('type', 'button');
        button.onclick = (ev)=> 
        
           const modalImg = document.getElementById("modalImg")
           const img = document.createElement("img");
           img.className = "appGifs"
           img.src = element.gifUrl
           
           modalImg.innerHTML = ''; // reset
           modalImg.appendChild(img);

           $('#exampleModalLongTitle').text(element.name);
           $('#exampleModalCenter').modal('show');
        
    );
   

【讨论】:

omg 我知道这很简单,我忽略了哈哈。非常感谢你

以上是关于将动态数据从数组对象插入到引导模式中 - vanilla javascript的主要内容,如果未能解决你的问题,请参考以下文章

如何将带有对象的数组中的数据动态添加到嵌套数组中?

如何从 react.js 中的 redux 存储向引导表插入数据?

使用foreach从动态post数组插入sql

从 laravel 中的数据库动态填充语言翻译数组

如何将数据从 django 传递到引导模式?

TypeError: $(...).modal 不是带有引导模式的函数