簡體   English   中英

Json級聯下拉菜單

[英]Json cascading dropdown

我正在嘗試使用JSON數據設置級聯下拉列表。 我有一些工作,但需要一些幫助才能使第二層按預期工作。 當前,它似乎正在獲取數組中的數字。

理想情況下,對於第二層,我想將下拉菜單中的文本顯示為選項文本,並且我想使用json中的id字段作為選項的值。

var data = {
            "Crime":[
                {"id":"1","text":"Number of police"},
                { "id":"2","text":"Number of crimes"} 
                    ],
            "Health":[
                {"id":"3","text":"Number of doctors"},
                {"id":"4","text":"Number of hospital visits"},
                {"id":"5","text":"Number of nurses"} 
                    ],
                }

我有一個jsfiddle顯示我到目前為止所擁有的。

很高興使用javascript / jquery的任何組合效果最佳。

您用於for..in的方式似乎不正確。 如果有針對性的集合(在這種情況下為data[this.value] )不是簡單數組,則question變量將不包含整個值。 相反,它將包含第一行,第二行的索引,依此類推。 我要求您閱讀此書以獲得更深入的了解:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

這條線在這里

questionSel.options[questionSel.options.length] = new Option(question, question);

必須這樣閱讀

questionSel.options[questionSel.options.length] = new Option(
                                      data[this.value][question].text, 
                                      data[this.value][question].id);

這是進行此更改后的更新小提琴:

http://jsfiddle.net/tc1f3kup/2/

請嘗試這個

 var data = {
        "Crime":[
            {"id":"1","text":"Number of police"},
            { "id":"2","text":"Number of crimes"} 
                ],

        "Health":[
            {"id":"3","text":"Number of doctors"},
            {"id":"4","text":"Number of hospital visits"},
            {"id":"5","text":"Number of nurses"} 

                ],

            }
 window.onload = function () {
        var themeSel = document.getElementById("theme"),
        questionSel = document.getElementById("questions");
        for (var theme in data) {
            themeSel.options[themeSel.options.length] = new Option(theme, theme);
        }
        themeSel.onchange = function () {
            questionSel.length = 1; // remove all options bar first
            if (this.selectedIndex < 1) return; // done                 
                for(var i=0;i<data[this.value].length;i++)
                {                        
                    questionSel.options[questionSel.options.length] = new Option(data[this.value][i].text, data[this.value][i].id);
                }



        }
}

工作小提琴http://jsfiddle.net/tc1f3kup/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM