使用JavaScript创建卡片元素吗?

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

我想制作一个简单的应用程序,允许用户在2个输入框中输入文本,单击按钮后,视图中会生成一个新的卡片元素。这与待办事项列表非常相似,但是大多数待办事项列表要么使用单个Div,要么使用并且仅通过用户输入来编辑列表。

我知道如何根据ID向现有的div或元素添加信息,并通常与用户输入配合使用,但是我不确定如何实际制作一个按钮,当单击该按钮时,会创建一个显示以下内容的“卡片”用户输入。

[基本上,我正在尝试创建待办事项应用程序,但是我希望每个待办事项列表项都连接到新的independent卡片元素,而不是经典的待办事项列表UI(显示无序列表)。我还希望如果用户单击其下方的删除按钮,则删除所有这些新卡片元素。

如果有人能指出正确的方向,我将不胜感激。

谢谢大家。

javascript html dom
1个回答
0
投票

这是使用JQuery的原始示例。如果需要的话,将其转换为原始Javascript应该并不难。

[基本上,您在这里所做的就是遍历所有待办事项,并为每个待办事项制作一个div(“卡片”)。该循环允许您基于待办事项的索引为每张卡添加自定义ID,并且这些值取自相应待办事项对象的属性。

然后,当您单击按钮时,只需将空白待办事项推入todos数组。

这里是HTML:

<div>
  <div id="todos-container">

  </div>

  <button id="btnAddtoList">Add</button>
</div>

和JS

let todos = [
  {input1: 'Input0-0', input2: 'Input0-1'},
  {input1: 'Input1-0', input2: 'Input1-1'}
];

function runEach() {
  $('#todos-container').html(''); // clear the list
  // create a new div for each todo
  $.each( todos, function( index, value ){
     var newCard = $(`<div class="todo card" id="card-${index}""><input type="text" value="${value.index1}" />Input 1 <input type="text" value="${value.index2}" />Input 2</div>`);
     $('#todos-container').append(newCard); // append the new card to the container
  });
}

$('#btnAddtoList').click(function(){
    todos.push({input1: '', input2: ''}); // add a todo
    runEach(); // run the function to re-add the cards
});

runEach();
© www.soinside.com 2019 - 2024. All rights reserved.