将样式对象的值指向对象

时间:2019-05-16 21:33:49

标签: javascript

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

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

      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

1 个答案:

答案 0 :(得分:3)

您的问题尚不清楚,因为您没有提供期望的结果,但是代码的目标是什么,但是我可以帮助您摆脱语法错误。

您的代码存在以下问题:

  • 您没有正确使用箭头功能。如果您打算在其中使用多个语句或定义变量,则应使用花括号,然后返回所需的结果。

  • 您没有正确使用模板文字。为了使它们起作用,必须将它们封装在反引号中。

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>