简体   繁体   中英

How do i make lists in a list, in a .js file and then choose a randomd list item using jquery/javascript?

(Coding in a .js file, not in the body of a .html)

So, if have a list: category = ['a', 'b', 'c'];

and every list item have themselft diffrent choices:

category[0] = ['long textstring1', 'longtextstring2', 'longtextstring3'];
category[1] = ['long textstring1', 'longtextstring2', 'longtextstring3'];
category[2] = ['long textstring1', 'longtextstring2', 'longtextstring3'];

First: How do i write a list in a list in my .js file? (Guessing you are not able to do like you would in a body with <ul> and <li> and so on)

Second: How do i randomly generate, a,b or c, and then a random list item within that list?

When i have my generated choice, i would very much like to print it out on the screen.

/W

You can make a list within a list just by using a multi-dimensional array as you did above. However, if you want a mapping like a -> [list], you need to use an object:

{"a": ['long textstring1'], "b": ['long textstring1']}

It is actually easier if you are using an array instead of an object to get the random property. For example:

var category = [['ls1', 'ls2'], ['ls1', 'ls2']];

Then you could get a random sub-list using:

var rand = category[Math.floor(Math.random() * (category.length + 1)) + min];

There are several answers on how to get a random property from a JS object

This might help you for the first part of your question, generating the lists based on your input:

var category = ['a', 'b', 'c'];
category[0] = ['long textstring1', 'longtextstring2', 'longtextstring3'];
category[1] = ['long textstring1', 'longtextstring2', 'longtextstring3'];
category[2] = ['long textstring1', 'longtextstring2', 'longtextstring3'];

var container = document.getElementById("container");
for(var i = 0; i < category.length; i++)
{
    var list = document.createElement("ul");
    for(var j = 0; j < category[i].length; j++)
    {
        var listItem = document.createElement("li");
        var txt = document.createTextNode(category[i][j]);
        listItem.appendChild(txt);
        list.appendChild(listItem);
    }
    container.appendChild(list);
}

JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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