我相信你已經加載的DOM JSON數據,所以你可以在你的JavaScript訪問數據。 您是否使用任何JavaScript庫或框架 - jQuery,AngularJS或純Javascript? 將外部JavaScript代碼組織爲擴展名爲.js的文件並將其加載到HTML中使用<script>
標籤<head>
或<body>
部分總是更好。
步驟來動態地生成錨標籤以HTML:
- 獲得從JSON數據到DOM對象(JavaScript的)
- 創建/跟蹤其中將包含選項父HTML元素。將此引用保存在一個變量中。
- 迭代到從JSON
- 訪問的數據陣列(或對象)獲取內每次迭代
- 的相關屬性的值創建將與每個數據值被重複使用的HTML元素。在這種情況下,模板應爲'值'
- 將此生成的代碼追加到上面#2中存儲的父元素中。
- 迭代完成後,將父元素注入(追加)到適當位置的DOM中。
案例1:普通的JavaScript -
使用XHR來讀取JSON和數據進入一個變量。讓我們將其命名爲JSONData。
我們將在JavaScript中保留在HTML中創建的父元素的引用。
//希望你只有一個元素與這一類名或
//有關元素是這個類名在此HTML代碼中的第一個元素。
//一般情況下,是一個很好的做法,我們應該要麼使用ID來我們的JavaScript代碼中單獨確定的元素,
//其他使用了相同的特定標識。
var parentDropdownContainer = document.getElementsByClassName('dropdown-content')[0];
迭代的JSON數據
for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
//we will add logic to generate HTML
}
可以使用迭代的其他變體 - 中,同時,方法Array.splice()等高達你的理解。
在這個迭代器,我們需要創建一個HTML代碼,並將其添加到父容器
for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
var currentData = JSONData[counter]; //this holds the reference of the current data in this iteration
var dropdownElement = document.createElement('a');
dropdownElement.setAttribute('href','#'); //this adds the href attribute into the anchor element.
//lets add another attribute to the anchor element to represent the dynamic id/value associated with this data
dropdownElement.setAttribute('data-value',currentData.A);
//lets add the value inside the anchor element
dropdownElement.innerHTML = currentData.B;
//lets append this element to the parent container
parentDropdownContainer.appendChild(dropdownElement);
}
現在,這應該呈現在下拉列表中所需的動態選項。
由於您添加了'javascript'標記,請同時包含您嘗試過的Javascript代碼,以便我們可以幫助您進行調試或改進。 – ITWitch