将JSON加载到datalist失败

时间:2015-12-07 09:20:34

标签: javascript json html-datalist

我尝试在datalist中添加两种方式的输入。为什么第一个不起作用? - > bootlply

var dataList = document.getElementById('json-datalist');

var jsonOptions = [{
                    "product": "11111",
                    "description": "description 1"
                  }, {
                    "product": "22222",
                    "description": "description 2"
                  }, {
                    "product": "33333",
                    "description": "description 3"
                  }, {
                    "product": "44444",
                    "description": "description 4"
                  }, {
                    "product": "55555",
                    "description": "description 5"
                  }]; 

jsonOptions.forEach(function(item) {

  var option = document.createElement('option');

  option.value = item.description;
  option.text = item.product;
  option.setAttribute('data-product', item.product);
  .
  dataList.appendChild(option);
});

然后

<div class="container">

    <div class="form-group">
         <div class="col-xs-4">
           <input class="form-control" name="description" type="text" id="ajax" list="json-datalist">
           <datalist id="json-datalist"></datalist>
         </div>


          <div class="col-xs-2">
            <datalist id="material">
              <option value="1">
              </option><option value="2">
              </option><option value="3">
            </option></datalist>
            <input type="text" list="material" class="form-control" name="material-0" placeholder="material">
          </div>

     </div>   




</div>

1 个答案:

答案 0 :(得分:0)

还有一个额外的.导致语法错误

  option.setAttribute('data-product', item.product);
  . // <-------------------------------------------- This is your enemy
  dataList.appendChild(option);

只需删除它即可。 :)

  option.setAttribute('data-product', item.product);
  dataList.appendChild(option);