123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- /* Рекурсия: HTML tree
- Используя решение этого задания сделайте функцию, которая рекурсивно создает HTML-строку из древовидной структуры данных Javascript любой вложенности. Проверьте результат работы функции выводя HTML-строку используя document.write или же какой-то_элемент.innerHTML*/
- const table = {
- tagName: 'table',
- attrs: {
- border: "1",
- },
- children: [
- {
- tagName: 'tr',
- children: [
- {
- tagName: "td",
- children: ["1x1"],
- },
- {
- tagName: "td",
- children: ["1x2"],
- },
- ]
- },
- {
- tagName: 'tr',
- children: [
- {
- tagName: "td",
- children: ["2x1"],
- },
- {
- tagName: "td",
- children: ["2x2"],
- },
- ]
- }
- ]
- }
- //htmlTree(table) //вернет <table border='1' ....
- let result = ""
- function recursion (obj, str="") {
- console.log(obj.tagName)
- result += "<" + obj.tagName
- if (obj.attrs){
- for (property in obj.attrs) {
- result += ' ' + property + '="' + obj.attrs[property] + '"'
- }
- }
- result += ">"
- console.log(obj.children)
-
- let children
- if (obj.children){
- children = obj.children
- for (const obj of children){
- console.log(obj)
- if (typeof obj !== 'object') {
- result += obj
- }
- if(typeof obj === 'object') {
- recursion (obj, str)
- }
- }
- }
- result += "</" + obj.tagName + ">"
- }
- recursion(table)
- console.log(result)
- result =""
- const body = {
- tagName : 'body',
- children : [
- {
- tagName : 'div',
- children : [
- {
- tagName : 'span',
- children : ['Enter a data please:']
- },
- {
- tagName : 'br'
- },
- {
- tagName : 'input',
- attrs : {
- type : 'text',
- id : 'name'
- }
- },
- {
- tagName : 'input',
- attrs : {
- type : 'text',
- id : 'surname',
- }
- }
- ]
- },
- {
- tagName : 'div',
- children : [
- {
- tagName : 'button',
- attrs : {
- id : 'ok'
- },
- children : ['OK']
- },
- {
- tagName : 'button',
- attrs : {
- id : 'cancel'
- },
- children : 'Cancel'
- },
- ]
- }
- ]
- }
- recursion(body)
- console.log(result)
|