javascript - 对象数组值以样式元素
问题描述
我正在使用此代码来获取选中的复选框并将其名称与对象数组匹配,以便能够检索一些值。样品小提琴。
如何使用这些值创建跨度元素并根据选中的复选框更新颜色设置位置?
var inputElements = document.getElementsByName("fruits");
const item = {
"lychee" :{ price:10, pos:80, colCode:'ff0000' },
"orange" :{ price:12, pos:60, colCode:'00ff00' },
"apple" :{ price:8, pos:40, colCode:'ff6600' },
"mango" :{ price:12, pos:60, colCode:'00ff00' },
"banana" :{ price:4, pos:80, colCode:'ff0000' }
};
let result = [...document.querySelectorAll("[name=fruits]:checked")]
.map(chk => (
var marker = document.createElement('span');
marker.style.color = colCode:${item[chk.value].colCode}, //does not work
marker.style.marginLeft = pos:${item[chk.value].pos}px ) //does not work
);
<input type="checkbox" name="fruits" value="lychee">Lychee <br>
<input type="checkbox" name="fruits" value="orange" checked>Orange <br>
<input type="checkbox" name="fruits" value="apple">Apple <br>
<input type="checkbox" name="fruits" value="mango" checked>Mango <br>
<input type="checkbox" name="fruits" value="banana">Banana
解决方案
由于您没有提供所需的结果,您的代码的目标是什么,您的问题非常不清楚,但我可以帮助您摆脱语法错误。
您的代码存在以下问题:
您没有正确使用箭头功能。如果你打算在其中使用多个语句,或者定义变量,你应该使用大括号,然后返回你想要的结果。
您没有正确使用模板文字。为了使它们起作用,它们必须用反引号括起来。
var inputElements = document.getElementsByName("fruits");
const item = {
"lychee": { price: 10, pos: 80, colCode: "ff0000" },
"orange": { price: 12, pos: 60, colCode: "00ff00" },
"apple": { price: 8, pos: 40, colCode: "ff6600" },
"mango": { price: 12, pos: 60, colCode: "00ff00" },
"banana": { price: 4, pos: 80, colCode: "ff0000" }
};
let result = [...document.querySelectorAll("[name=fruits]:checked")].map(chk => {
/* Create a <span> element. */
var marker = document.createElement("span");
/* Set the properties using template literals. */
marker.style.color = `#${item[chk.value].colCode}`;
marker.style.marginLeft = `${item[chk.value].pos}px`;
/* Put some content into the <span>. */
marker.textContent= "Content";
/* Append the <span> into the wrapper. */
wrapper.appendChild(marker);
/* Return the <span> so that it's cached inside the results array. */
return marker;
});
<input type="checkbox" name="fruits" value="lychee" checked>Lychee <br>
<input type="checkbox" name="fruits" value="orange" >Orange <br>
<input type="checkbox" name="fruits" value="apple" checked>Apple <br>
<input type="checkbox" name="fruits" value="mango" checked>Mango <br>
<input type="checkbox" name="fruits" value="banana">Banana
<div id = "wrapper"></div>
推荐阅读
- python - 在 SQL IN 语句内的数据框中使用一行
- reactjs - 如何根据项目列表使用 React Hooks、功能组件和功能防止不必要的重新渲染
- ruby-on-rails - 当我在 vscode 中保存时,我在 .erb 文件中的 ruby 代码丢失了缩进
- javascript - Django 频道或定期 ajax 请求?
- php - WordPress 在更改站点 URL 以使用 Weglot 翻译插件后出现 500 服务器错误
- c# - 如何修复 ASP.NET 中的“System.IO.IOException:无法从传输连接读取数据:连接已关闭”?
- python - Python SQLite3 OperationalError:表店有 2 列,但提供了 3 个值
- windows - Kestrel 如何在相似或重复的 TLS 证书中进行选择?
- google-cloud-platform - Google Cloud Speech-to-text 非常不准确,最后一个结果包含所有其他结果,并且仅在最后一个结果中包含 speakerTag
- node.js - Nodejs Xml 到 Json xml2js