使按钮组动态化

时间:2019-01-26 17:05:17

标签: javascript jquery django

我有来自第三部分API的数据,我可以使用JQuery将其解析为多个要在图表中显示的数组。我将其删除以简化代码,并使用了两个固定数组newData1和newData2

我已经成功创建了可以在两个数据数组之间切换并更改图表的按钮,因此图表是动态的,并且在单击按钮时发生了更改

我无法解决的问题是如何使按钮的数量动态化并从列表中填充按钮的数量-长度可能有所不同,并取自名为button_list的数组

函数printBn确实创建了一个动态按钮列表,但我没有出现为按钮组,而是采用了我尝试应用的Bootstrap样式

<div class="btn-group-vertical" role="group" aria-label="First group">
    <button id="btn1" type="button" class="btn btn-secondary">1</button>
    <button id="btn2" type="button" class="btn btn-secondary">2</button>
</div>

我基本上想要一种使Bootstrap html动态的方法

charts.html

{% extends 'base.html' %}

<script>
{% block jquery %}

var endpoint = '/api/data/';
var newData1 = [0.9, 0.9, 0.9];
var newData2 = [0.2, 0.2, 0.2];
var data = [];
var button_list = ['Test1', 'Test2', 'Test3', 'Test4'];

//create an array of arrays
data.push(newData1)
data.push(newData2)

var labels = ['Label1', 'Label2', 'Label3'];
const context = document.querySelector('#myChart1').getContext('3d');

//switch between the arrays and change the data in the chart
$("#btn1").on("click", function() {
    setChart('radar', 'myChart1', labels, data[0])
});
$("#btn2").on("click", function() {
    setChart('radar', 'myChart1', labels, data[1])
});

 //this is my attempt at dynamic a dynimic button group
function printBtn() {
    for (var i = 0; i < button_list.length; i++) {
        var btn = document.createElement("button");
        btn.className = 'btn-secondary';
        var t = document.createTextNode(button_list[i]);
        t.className='btn-group-vertical';
        btn.appendChild(t);    
        document.body.appendChild(btn);
    }
}


$.ajax({
    method: "GET",
    url: endpoint,
    success: function(data){  
        //the Json will be parsed here and an array 
        setChart('radar', 'myChart1', labels, newData1)
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
})

//Create chart
function setChart(chart_type, chart_name, label_array, data_array){
    var ctx = document.getElementById(chart_name);
    var myChart = new Chart(ctx, {
    type: chart_type,
    scaleSteps: 10,
    // Number - The value jump in the hard coded scale
    scaleStepWidth: 10,
    // Number - The scale starting value
    scaleStartValue: 0,
    data: {
        labels: label_array,
        datasets: [{
            data: data_array,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)'             
            ],
            borderColor: [
                'rgba(255,99,132,1)'
            ],
            borderWidth: 1
        }]
    },
    options: {title: {
                    display: true,
                    text: 'Custom Chart Title',
                    fontSize: 20
                },
               legend: {display: false
                        },
                scale: {ticks: {
                                display: false,
                                beginAtZero: true,
                                min: 0,
                                max: 1,
                                stepSize: 0.2
                              },
                        pointLabels: {
                                  fontSize: 20
                                }
                }
    }
});
}

{% endblock %}
</script>


{% block content %}
<div class="container">
    <div class='col-lg-12' url-endpoint='{% url "api-data" %}'>
        <div class="btn-group-vertical" role="group" aria-label="First group">
            <button id="btn1" type="button" class="btn btn-secondary">1</button>
            <button id="btn2" type="button" class="btn btn-secondary">2</button>
        </div>
        <div class='col-sm-6'>
            <canvas id="myChart1" width="400" height="400"></canvas>
        </div>
    </div>
</div>

{% endblock content %}

1 个答案:

答案 0 :(得分:1)

尝试一下:

function makeBtns(arr, tObj) {
  $.each(arr, function(k, v){
    var btn = $("<button>", {
      class: "btn-secondary",
      id: v
    }).html(v).appendTo(tObj);
  });
}

然后将其用作:

makeBtns(button_list, $("body"));

这会将4个按钮附加到body的末尾,HTML将是:

<button id="Test1" class="btn-secondary">Test1</button>
<button id="Test2" class="btn-secondary">Test2</button>
<button id="Test3" class="btn-secondary">Test3</button>
<button id="Test4" class="btn-secondary">Test4</button>

您可能会考虑使用更复杂的数组。

button_list = [{
  element: "button",
  attributes: {
    id: "test-1",
    class: "btn btn-secondary",
    type: "button"
  },
  label: "Test 1"
},{
  element: "button",
  attributes: {
    id: "test-2",
    class: "btn btn-secondary",
    type: "button"
  },
  label: "Test 2"
}];

这需要稍微轻一点的功能。

function makeBtns(arr, tObj, replace) {
  if(replace == undefined){
    replace = false;
  }
  if(replace){
    tObj.html("");
  }
  $.each(arr, function(k, v){
    var btn = $("<" + v.element + ">", v.attributes).html(v.label).appendTo(tObj);
  });
}

我建议使用以下代码替换您的静态按钮。函数中添加的行为y6ou提供了清空目标并附加选项的选项。缺省值是false,它会附加在其后。

makeBtns(button_list, $(".container > div > .btn-group-vertical"), true);

希望这会有所帮助。