简体   繁体   English

附加选项标签以使用JQuery从数组中选择标签

[英]Appending option tags to select tag from array using JQuery

I am trying to create an options drop down list in html using JQuery to append from an Array. 我正在尝试使用JQuery从Array追加HTML中的选项下拉列表。

Everything appears to be working correctly apart from the text between the opening & closing tags is not appearing. 除了开始和结束标记之间的文本没有出现以外,其他所有内容似乎都正常工作。 Am I so tired i'm missing a simple typo or doing something wrong?!? 我很累我错过了一个简单的错字或做错了什么吗?!

The JS and JQuery code is: JS和JQuery代码为:

var displayMenuSelections = function(){
  var menuSelection = menu[0].prices[0];
  var menuItems = Object.keys(menuSelection);
  menuItems.forEach(menuFunction);
}

function menuFunction(item){
  $('#menu').append($('<option value="' + item + '">' + item + '</option'));
}

The result of a typical option tag looks like this (with the 'item' missing between the opening and closing tags): 典型的选项标签的结果如下所示(开始和结束标签之间缺少“ item”):

<option value="Cafe Latte"></option>

You forgot the > for the closing option tag. 您忘记了>作为结束选项标签。 JQuery tries to close it for you, and in the process the inner item text doesn't get set. jQuery尝试为您关闭它,在此过程中,内部项目文本未设置。

Jquery takes a philosophy where it sort of tries to work with whatever you give it - this can be both good and bad, but in this case it makes it harder to debug since there's no error/exception that is raised. jQuery遵循一种哲学,即尝试与您提供的任何东西一起工作-这可能是好事,也可能是坏事,但是在这种情况下,由于没有引发错误/异常,因此它使调试变得更加困难。

var displayMenuSelections = function(){
  var menuSelection = menu[0].prices[0];
  var menuItems = Object.keys(menuSelection);
  menuItems.forEach(menuFunction);
}

function menuFunction(item){
  $('#menu').append($('<option value="' + item + '">' + item + '</option>'));
}

It looks to me like you are not passing your parameter 在我看来,您没有传递参数

item

to your function 对你的功能

menuFunction(item)

I'm just assuming you are trying to send 我只是假设您正在尝试发送

var menuSelection

so you can try changing your function call to 因此您可以尝试将函数调用更改为

menuItems.forEach(menuFunction(menuSelection));

I have not tested this however! 我还没有测试过!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM