首页 > 解决方案 > 对象数组值以样式元素

问题描述

我正在使用此代码来获取选中的复选框并将其名称与对象数组匹配,以便能够检索一些值。样品小提琴。

如何使用这些值创建跨度元素并根据选中的复选框更新颜色设置位置?

      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

标签: 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 => {
    /* 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>


推荐阅读