开发者

Javascript function to display items in an array as a vertical list?

开发者 https://www.devze.com 2023-02-28 22:30 出处:网络
I\'m developing a little website that allows the user to earn achievements based off a specific number of accomplishments. And I\'m looking for a clean way to print the earned accomplishments on the s

I'm developing a little website that allows the user to earn achievements based off a specific number of accomplishments. And I'm looking for a clean way to print the earned accomplishments on the screen from an Array.

Basically I want a vertical list d开发者_运维百科isplay of an array that can update based on user interaction.

currently I have this:

function win() {
check = Number(localStorage.snum);

switch(check) {

    case 50:
    prizes.unshift('50: You infant');
    localStorage.priz = prizes;
    document.getElementById('awards').innerHTML = prizes;
    break;

    case 100:
    prizes.unshift('100: big whoop');
    localStorage.priz = prizes;
    document.getElementById('awards').innerHTML = prizes;
    break; 
}
}

and in the html I have

<div id="numbox"> </div>
<div id="awards"></div>

Amongst other things.

I would ideally like an 'Achievement box" that displays the array as a vertical list.

Help?

EDIT: I took out <br /> That I had in there as a hackjob vertical list.

I guess an Array would look like var prizes= new Array('50: You infant', '100: big whoop');


For a start:

var awards = {
    50: 'You infant',
    100: 'big whoop'
};

function win() {
    var points = +localStorage.snum; // shortcut to convert to a number
    if(points in awards) {
        var prize = awards[points];
        prizes.unshift(prize);
        localStorage.priz = prizes; // not sure if you really need this

        var list = document.getElementById('awards');
        var li = document.createElement('li');
        li.innerHTML = points + ': ' + prize;
        list.insertBefore(li, list.firstChild); // inserting at the beginning
    }
}

with this HTML:

<ul id="awards"></ul>

Using this kind of map makes it easier to extend it later ( I don't think you want to write a thousand case statements ;)).

You can style the list however you want to with CSS.

Update: DEMO, another DEMO

0

精彩评论

暂无评论...
验证码 换一张
取 消