2 回答
TA贡献1784条经验 获得超9个赞
您需要知道使用嵌套optgroup元素的方法是行不通的,因为只会optgroup显示第一层:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup
尝试使用类似的东西:
const path = (source = {}) => {
// Let the initial string be empty
let returnedString = '';
// Convert the object into an array using key/value pair and then iterate through it
Object.entries(source)
.forEach(([key, value]) => {
if (typeof value === 'object' && value !== null) {
// value is an object, iterate through it
returnedString += `<optgroup label="${key}">${path(value)}</optgroup>`;
} else {
// value should be a string
returnedString += `<option value="${key}">${value}</option>`;
}
});
// Return the string
return returnedString;
}
此外,在操作 DOM 时,建议使用内置方法来操作元素而不是字符串:
// Create the "root" element
// const root = document.createElement('select');
const path = (source = {}, rootElement = undefined) => {
// Define the root element if not an instance of Element
const root= rootElement instanceof Element ? rootElement : document.createElement('select');
// Convert the object into an array using key/value pair and then iterate through it
Object.entries(source)
.forEach(([key, value]) => {
if (typeof value === 'object' && value !== null) { // value is an object, iterate through it
// Create an optgroup element
const optgroup = document.createElement('optgroup');
// Defines the attributes
optgroup.setAttribute('label', key);
// Add "content" inside the optgroup
path(value, optgroup);
// Append the newly created optgroup element to the root
root.appendChild(optgroup);
} else { // value should be a string
// Create an option element
const option = document.createElement('option');
// Defines the attributes
option.setAttribute('value', key);
option.text = value;
// Append the newly created option element to the root
root.appendChild(option);
}
});
// Return the root element
return root;
}
编辑 1:在答案中添加了 DOM 方式
optgroup编辑 2:添加嵌套警告
TA贡献1786条经验 获得超11个赞
function getMyTypes(obj_myTypes) {
var targetHTML = $("");
for (const key in obj_myTypes) {
if (obj_myTypes.hasOwnProperty(key)) {
var element = obj_myTypes[key];
console.log(key)
targetHTML.prepend(`<optgroup id="one" label="${key}"> ${key} </optgroup>`);
//each in obj
//console.log(element)
stepTwo(element)
}
}
}
getMyTypes(myTypes);
function stepOne() {
var step_one = $('optgroup').filter('[id="one"]');
step_one.each((index) => {
// var result = $(this).text()
step_one.prepend(`<optgroup id="two" label=""> two </optgroup>`)
});
}
stepOne()
function stepTwo(obj_elem) {
var step_two = $('optgroup').filter('[id="two"]');
for (const key in obj_elem) {
if (obj_elem.hasOwnProperty(key)) {
var item_of_element = obj_elem[key];
console.log('KEY: '+key)
step_two.each((index,html_element) => {
$(html_element).attr("label", value)
console.log(value)
//return value
});
}
}
}
添加回答
举报