根据json值创建复选框

时间:2018-09-29 17:48:24

标签: javascript html json menu

我的json看起来像这样

[ {
        "type": "quant",
        "name": "horizontalError",
        "prop": [
            0.12,
            12.9
        ]
    },
    {
        "type": "categor",
        "name": "magType",
        "prop": [
            "ml",
            "md",
            "mb"
        ]
    }]

我已经使用每个对象的“名称”属性创建了下拉菜单。现在,我尝试根据用户在下拉菜单中选择的名称来创建复选框(如果类型是类别)和滑块(如果类型是quantum)

我已经走了,但是被困在这里了

d3.json("hashmap.json", function(error,data) {
    if(error) {console.log("error fetching data");}

var hashap = data;



var dropDown = d3.select("#sel").selectAll("option").data(hashap).enter().append("option").text(function(d) { return d.name} ).attr("value",function(d, i) {
         return i;});

    d3.select("#sel").on("change", function() {
          var checkSlider = d3.select("#checkSlider"); // clearing previous checkbox or slider
          if(hashap[this.value].type == "categor") {
            console.log(hashap[this.value].prop.length);
            for(var i =0; i >= hashap[this.value].prop.length; i++){
            checkSlider.append("input").attr("type","checkbox");
            checkSlider.append("label").text(hashap[this.value].prop[i]);
          }
          }
          else {
            checkSlider.append("input").attr("type","range").attr("min", hashap[this.value].prop[0]).attr("max", hashap[this.value].prop[1]);
            checkSlider.append("label").text(hashap[this.value].name);      
          }
        });

1 个答案:

答案 0 :(得分:0)

我在代码中添加了注释。希望这会有所帮助

    var hashap = [ {
        "type": "quant",
        "name": "horizontalError",
        "prop": [
            0.12,
            12.9
        ]
    },
    {
        "type": "categor",
        "name": "magType",
        "prop": [
            "ml",
            "md",
            "mb"
        ]
    }];
    
   // creating drop down  
	var dropDown = d3.select("#dropdown").selectAll("option").data(hashap).enter().append("option").text(function(d) { return d.name} ).attr("value",function(d, i) {
	return i;});
  
  // adding onchange function 
	d3.select("#dropdown").on("change", function() {
		var checkSlider = d3.select("#checkSlider").html(""); // clearing previous checkbox or slider
		if(hashap[this.value].type == "categor") {
			checkSlider.append("input").attr("type","checkbox");
			checkSlider.append("label").text(hashap[this.value].name);
		}
		else {
			checkSlider.append("input").attr("type","range").attr("min", 0).attr("max", 100);
			checkSlider.append("label").text(hashap[this.value].name);			
		}
	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<select id="dropdown" ></select>
	<div id="checkSlider"><div>