简体   繁体   English

chart.js label 带if语句

[英]chart.js label with if statement

for traduction purposes, I am trying to set up my chart.js labels based on html tag text.出于翻译目的,我正在尝试根据 html 标签文本设置我的 chart.js 标签。 Being a beginner to javascript, this a bit of a challenge.作为 javascript 的初学者,这有点挑战。

Here is what I am trying to do:这是我正在尝试做的事情:

html code: html 代码:

<div class="col-lg-6">
  <div id='tag4' class="card-footer small text-muted">{% trans 'ITEMS IN DIFFICULTY' %}</div>
  <div class="bar-chart block">
    <canvas id="myChart3" height="175"></canvas>
  </div>

and my chart.js code:和我的 chart.js 代码:

var myChart3 = new Chart(ctx3, {
  type: 'bar',
  data: {
    labels: labels3,
    datasets: [{
      label: if (document.getElementById('tag4').value == 'ITEMS IN DIFFICULTY') {
        'low performing items (quantity sold/week)'
      }
      else {
        'references en difficulté (quantité vendu/semaine)'
      },
      data: defaultData3,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
      ],
      borderWidth: 1
    }],
    options: {
      scales: {
        yAxes: [{
          gridLines: {
            drawOnChartArea: false,
            ticks: {
              beginAtZero: true
            }
          }
        }],
      }
    }
  }
})

the result is that the graph does not show up.结果是图表没有显示出来。 I am not sure if the issue is because there is something wrong with my if statement or if its not something that can be done with chart.js labels.我不确定问题是因为我的 if 语句有问题,还是不能使用 chart.js 标签完成。 Any help is more than welcomed!任何帮助都非常受欢迎!

What you need is a ternary operator, it works like this:你需要的是一个三元运算符,它的工作原理是这样的:

let isTrue = true
let a = isTrue ? 1 : 0

if isTrue is true, then a is 1, if false, a is 0如果isTrue为真,则a为 1,如果为假,则a为 0

In your case, you can pass following as a label:在您的情况下,您可以将以下内容作为 label 传递:

document.getElementById('tag4').textContent == 'ITEMS IN DIFFICULTY' ? 'label if true' : 'label if false'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM