Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
How to display array element on click event with D3JS

I just started learning D3Js and I'm struggling with a basic idea.

Let's say I have an array:

let arr = [a, b, c, d];

And, I have a button in the HTML

<input type="button" id="btn" value="Click">

Using the d3js, I want to print out (e.g., console.log) to print elements in the array one by one in order. In other words, the first button click prints 'a', the second click 'b', and so on then starts from 'a' again after hitting the last element.

Below is my attempt, which isn't working.

d3.select("#btn").data(arr).enter().on("click", function(d) { return console.log(d)});

Can someone help me with the idea of how I can get this working?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I understand you correctly we can do this fairly easily (with or without D3). As you're asking about D3, I'll show a soluation with it.

You are using .data() and .enter() - these are used when you want to create an element for every item (datum) in the data array - but you only have one element, that already exists. Since we don't need to enter anything and we have only one datum, these two methods aren't what you are looking for. Also, enter is usually followed up with .append() which creates the entered elements - without that you aren't assigning the on listener to any clickable element.

Instead, we can bind an individual datum containing an array of values to the button:

 .datum(arr)

But, we can create a more useful datum than that by also including a property for the current index so that everything we need is self conained:

.datum({i:0,arr:arr})

Then we can assign a click listener to the button which accesses the datum, logs the value of arr[i] and increments i. Below I use the modulus operator to avoid ever having to reset i to 0:

let arr = ["a", "b", "c", "d"];

d3.select("input")
  .datum({i:0, arr:arr })
  .on("click", function(d) {
    console.log(d.arr[d.i++%d.arr.length])
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<input type="button" id="btn" value="Click">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda