Array items relating to adding new item

3

I have a array that has 10 items, for example:

var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

And in my html, I have several buttons, with id's, for example:

<button id="item_12">12</button>
<button id="item_27">27</button>
<button id="item_54">54</button>

However, I would like that, when I click on a button, I add the id in the array in the first item, and the others move on to the next item, for example (if I clicked the button with id = item_54):

var array_exemplo = ["item_54", "item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9"];

How can I do this?

    
asked by anonymous 28.11.2015 / 02:13

1 answer

3

Use the unshift method that inserts a new value at the beginning of the array list:

    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    var button = document.getElementById("item_54");

    button.onclick = function(){

        array_exemplo.unshift(this.id);

    }

If you want to do this in HTML:

HTML

<input type="button" id="item_54" onclick="addId(this.id)">

JS

    var array_exemplo = ["item_1", "item_2", "item_3", "item_4", "item_5", "item_6", "item_7", "item_8", "item_9", "item_10"];

    function addId(Id){

        array_exemplo.unshift(Id);

    }
    
28.11.2015 / 02:19