javascript - 选择构建文本列表 HTML 的项目
问题描述
我正在尝试找出一种方法,以便您可以创建比萨店(或任何餐厅)的在线订购流程,这只是我选择的示例。这个想法是,当单击选项选项时,选定的项目将填充一个文本值,将可用选项中的所有选项添加到预先存在的列表中。例如,如果我想要一个“Viennese”和一个“Norcia e Funghi”,我会首先选择 Viennese(它会在文本中),然后选择 Norcia e Funghi,然后将其添加到文本列表中。
这是我想出的最好的方法(当然是在互联网的帮助下),我正在努力在大流行期间提高自己的技能,非常感谢您的帮助!我被困住了!
<html>
<head>
<script type="text/javascript">
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
document.getElementById("test").innerHTML = text;
}
</script>
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div
</body>
</html>
解决方案
如果我理解正确,您希望在<div id="test"></div>
每次从列表中选择项目时更新而不是替换的内容。
<html>
<head>
<script type="text/javascript">
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
//Check the items already outputted for the exact text
//Use ... operator to convert into array
var textItems = [...document.getElementById("test").children];
//Filter through the elements to find one that includes matching text
existingItem = textItems.filter(element => element.innerHTML.includes(text));
// If there is an item with the text, then split the text by our seperator and add 1 to it before setting the inner text once more
if (existingItem.length) {
var itemAndQuantity = existingItem[0].innerText.split("-");
var newQuantity = 1 + parseInt(itemAndQuantity[1]);
existingItem[0].innerHTML = itemAndQuantity[0] + " - " + newQuantity;
} else {
//Create a new paragraph element, this could be a <li> instead
var paragraph = document.createElement("p");
//Add a - 1 for the quantity
paragraph.innerHTML = text + " - 1";
document.getElementById("test").appendChild(paragraph);
}
}
</script>
</head>
<body>
<select id="box1" onChange="myNewFunction(this);">
<option value="1">Nessuna</option>
<option value="2">Viennese</option>
<option value="3">Norcia e Funghi</option>
</select>
<div id="test"></div>
</body>
</html>
每次从下拉列表中选择一个项目时,这将向您的 div 添加一个新的段落元素。
推荐阅读
- ios - Xcode 10、Swift 4.2 中的“歧义使用”
- python - 从另一个 Dataframe 中的一个 Dataframe 中查找元素并返回其索引的快速方法
- laravel - 如果记录部分出现在另一个表中,如何将它们标记为红色/绿色?
- amazon-dynamodb - DynamoDB - 无法“转义”输入
- python - 可变利率。当利息符合条件时,我怎样才能让利率切换
- python - 获得熊猫系列对象的平均值
- angularjs - 如果用户离开域,则获取用户对 beforeunload 事件的响应
- javascript - 我想根据输入文本框中的标记更改学生标签的颜色,但我的 java 脚本代码有问题
- tfs - 根据字段的值变化查询 TFS
- angular - 在功能模块中声明服务的最佳方式是什么?