如何为数组中的每个单击元素动态更改信息模式 innerHTML

How to dynamically change info modal innerHTML for each clicked element from an array

我正在尝试收集一小部分食谱,其中四个已经存储在一个对象数组中,每个对象代表另一个食谱。我的问题是我想制作一个信息 window,如果您愿意的话,它是一个模态,它将显示有关存储在其对象内的每个单击食谱的信息。

问题是,每当我尝试设置所述模式的 innerHTML 时,我创建的 for 循环都会显示整个对象,到目前为止,我还没有找到如何让每次点击模式只显示一个食谱的信息。 (第一个 link 应该显示第一个配方的详细信息,第二个显示第二个,依此类推)。

我尝试了一个 for 循环,它应该根据点击的元素动态循环信息 window 的内容,但它显示了整个对象,到目前为止我不确定还有什么其他方法是更好的解决方案.

我的对象数组如下所示

var recipes = [
{
    key: 0,
    title: 'Pasta Carbonara',
    ingredients: 'etc',
    instructions: 'etc'
},
{
    key: 1,
    title: 'etc',
    ingredients: 'etc',
    instructions: 'etc'
},
and so on (4 objects)
]

我的 for 循环看起来像这样:

function openModal() {
    detailsModal.style.display = 'block';
    var modalContent = document.getElementById('modalInfo');
    var modalBody = ''; 
    for (var i=0; i < recipes.length; i++){
        modalBody += JSON.stringify(recipes[i]) 
    }
    modalContent.innerHTML = modalBody;
}

完整代码在这里:https://codepen.io/Ellie555/pen/KOwexB

这个问题很普通,但如果您有任何建议,我将不胜感激。

一种方法是向锚点添加数据属性:

<a href="#" data-recipe-index="0">Pasta Carbonara</a>

然后使用这些属性来指示您的模态代码加载哪个配方:

function openModal(e) {
    detailsModal.style.display = 'block';
    var modalContent = document.getElementById('modalInfo');
    // The critical line:
    var modalBody = JSON.stringify(recipes[parseInt(e.currentTarget.dataset.recipeIndex)]);
    modalContent.innerHTML = modalBody;
}

完整代码:https://codepen.io/mac9416/pen/BXyPdO

旁白:为了方便访问,我会 use <button> elements 将样式设置为链接而不是锚点。

你上面的标记不是语义的 html 因为你没有重定向或导航。所以首先我会用 <button type="button">...</button>:

替换 <a href="#">...</a> 标签
<div class="main">
  <div class="recipes" id="recipeSection">
    <div class="recipe-entry">
      <div class="name"><button type="button" id="0">...</button></div>
    </div>
    <div class="recipe-entry">
      <div class="name"><button type="button" id="1">...</button></div>
    </div>
    <div class="recipe-entry">
      <div class="name"><button type="button" id="2">...</button></div>
    </div>
    <div class="recipe-entry">
      <div class="name"><button type="button" id="3">...</button></div>
    </div>
  </div>
</div>

回答您的问题以动态更改数组中每个单击元素的信息模式 innerHTML!

  1. id 添加到将被单击以将其与数组中所需对象相关联的每个元素
  2. 根据点击目标及其 id
  3. 过滤该数组
const data = recipes.filter(recipe => recipe.key === Number(event.target.id)); 
modalContent.innerHTML = JSON.stringify(data[0]);

我分叉并修改了你的代码。这是一个有效的 Demo.

注:

如果您不确定数组中每个项目的 key 值(即动态),您可以迭代它并将其附加到您的 DOM.

您也可以从 Javascript 创建列表,而不是在 HTML 中静态创建它。

我的代码在这里有注释: https://stackblitz.com/edit/js-bu6tz8?file=index.js