bluebelt.html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. var someTree = {
  11. tagName: "table", //html tag
  12. subTags: [ //вложенные тэги
  13. {
  14. tagName: "tr",
  15. subTags: [
  16. {
  17. tagName: "td",
  18. text: "some text",
  19. },
  20. {
  21. tagName: "td",
  22. text: "some text 2",
  23. }
  24. ]
  25. }
  26. ],
  27. attrs:
  28. {
  29. border: 1,
  30. },
  31. }
  32. var element = ""
  33. function toHtmlStr(obj) {
  34. if (obj.tagName !== undefined){
  35. element+= "<" + obj.tagName
  36. if (obj.attrs !== undefined) {
  37. let attrs = obj.attrs
  38. for (let key in attrs) {
  39. element += ` ${key}=${attrs[key]}` + ">\n"
  40. }
  41. } else {
  42. element += ">\n"
  43. }
  44. if (obj.text !== undefined) {
  45. element += `${obj.text}`
  46. }
  47. if (obj.subTags !== undefined) {
  48. let children = obj.subTags
  49. for (let i = 0; i < children.length; i++) {
  50. let childrenObj = children[i]
  51. toHtmlStr(childrenObj)
  52. }
  53. element+= `</${obj.tagName}>\n`
  54. } else {
  55. element+= `</${obj.tagName}>\n`
  56. }
  57. }
  58. return element
  59. }
  60. toHtmlStr(someTree)
  61. document.write(element)
  62. function toHtml(obj) {
  63. var element = document.createElement(obj.tagName);
  64. if (obj.text !== undefined) {
  65. element.innerHTML = obj.text
  66. }
  67. if (undefined !== obj.attrs) {
  68. for (let key in obj.attrs) {
  69. element[key] = obj.attrs[key]
  70. }
  71. }
  72. if (obj.subTags !== undefined) {
  73. for (let i = 0; i < obj.subTags.length; i++) {
  74. element.appendChild(toHtml(obj.subTags[i]));
  75. }
  76. }
  77. return element;
  78. }
  79. // document.body.appendChild(toHtml(someTree));
  80. </script>
  81. </body>
  82. </html>