通过javascript中的对象数组创建在线菜单(我是编码新手)

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

html

<div class="content"></div>

对象数组:

  var obj = [
   {
     title : "burger",
     price : 5
   },
   {
    title : "salad", 
    price : 10
   }
  ] 

功能:

function addItems() {
    $(".content").html('<div id="title"></div><div id="price"></div>');
};

function addContent() {
   $("#title").text(obj[i].title);
   $("#price").text(obj[i].price);
};

然后我循环浏览以更改html和内容:

for(i = 0; i < obj.length; i++){
   addItems();
   addContent();
}

结果:

是obj [2] .title“ salad”中的文本字符串。我想要这个结果

汉堡5沙拉10

感谢您的帮助

jquery for-loop dom-manipulation
2个回答
0
投票

您的代码存在多个问题。

1)您的addItem函数不是添加项目而是替换项目。 html()正在用新内容替换实际的html内容。尝试使用append()而不是html()。

2)您的addCOntent始终添加到同一项目,因为您只有一个id,即“ title”。如果使用addItem()添加另一个项目,则将有两个具有相同ID的div,这是禁止的。因此,您必须在ID中添加一个标识符。

e.G。

function addItems(id) {
     $(".content").append('<div id="title_'+id+'"></div><div id="price_'+id+'"></div>');
}

function addContent(id) {
   $("#title_"+id).text(obj[id].title);
   $("#price_"+id).text(obj[id].price);
};

for(let id = 0; id < obj.length; id++) {
   addItems(id);
   addContent(id);
}

0
投票

您的代码中有几个问题。

Firtsly,您正在将函数addContentaddItems的范围与for -loop的范围混合在一起。如果需要在函数内部使用仅在另一个作用域内已知的变量,则应将其传递给函数。这使您的代码更具可读性和不可理解性。没有人会通过您的函数声明知道,您实际上需要该函数中的项目数据]

这意味着,您必须声明您的函数,以便它可以与参数一起使用:

function addItem( item ) {
  // use the item data inside this function
  // also note that i changed the functions name, 
  // since you are only adding one item
}

第二,您试图将具有相同ID的多个元素添加到HTML。那将是无效的HTML,因为ID必须是唯一的。您很不走运,因为函数.html()替换了给定对象中的整个HTML,因此您最终只拥有一个#title#price ID。相反,您可以使用append()函数,该函数会将给定元素附加到html,因此您的addItem函数将获得:

function addItem( item ) {
  let html = "<div class='title'>"+item.title+"</div><div class='price'>"+item.price+"</div>";
  $('.content').append( html );
}

您的addContent函数现在是多余的,实际上会使代码过于复杂。

var obj = [
   {
     title : "burger",
     price : 5
   },
   {
    title : "salad", 
    price : 10
   }
];

function addItem( item ) {
  let html = "<div class='title'>"+item.title+"</div><div class='price'>"+item.price+"</div>";
  $('.content').append( html );
};

for(i = 0; i < obj.length; i++){
   addItem( obj[i]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div>
© www.soinside.com 2019 - 2024. All rights reserved.