Chinovski Chinovski - 11 months ago 40
Javascript Question

How to show ul items on click?

This is my code:

var nbrCliques = 0;
var selecteur = "#art"+nbrCliques;

$('#clique').on('click', function() { $(selecteur).show();});
$(selecteur).on('click', function() { nbrCliques++; selecteur="#art"+nbrCliques; $(selecteur).show(); });

.item {
display: none;

<script src=""></script>
<h1 id="clique">Liste des articles !</h1>
<li class="item" id="art0">Article 1</li>
<li class="item" id="art1">Article 2</li>
<li class="item" id="art2">Article 3</li>
<li class="item" id="art3">Article 4</li>

Well, what I am trying to do is to show the article N+1 when I click on the article N. I used different CSS selectors before, but I finally chose this code. The problem is that it works only for the first item, when I click on "Liste des articles" it shows item 1, when I click on it it shows item 2, but when I click on item 2 it doesn't show item 3, it is showen only by clicking on item 1, the same thing for item 4.

I cannot find the problem because I used consol.log to show variables and it seems changing, but finally it doesn't work.

Could you help me? Thank you in advance :D


I think it's a bad idea to keep a global variable of the number of clicks and calculate based off that when you can just use this to figure out which id was clicked, then add one to that.

I got it working by doing a $(".item").click() to get all the clicks on articles, then I used a string split to get the number of the article, next I added one to that id. Finally I show the item using the new selector.

JS: (I didn't modify any html or css)

var nbrCliques = 0;
var selecteur = "#art" + nbrCliques;

$("#clique").click(function() {
  //show the first item when they click the <h1>

$(".item").click(function() {
  //get id number of clicked element as string. for example art0 -> "0"
  var thisId ="art")[1];

  //convert to integer and add one
  var newId = parseInt(thisId) + 1;

  //build new selector for art(n+1)
  var newSelector = "#art" + newId;

  //finally show the item using the new selector

Note that the $(".item").click() function can be reduced to just this (I just wanted to show what the code was doing)

$(".item").click( function () {
    $("#art" + String(parseInt("art")[1]) + 1)).show()