首页 > 解决方案 > 使用 kotlinx.html 通过迭代构建 HTML

问题描述

我正在尝试通过迭代一个集合来使用 kotlinx.html 构建一个 HTML 列表,对于集合中的每个元素,我想在 UL 标记内构建一个 LI 标记。

这就是我正在尝试的:

fun showProducts(products: List<Product>) {
    document.getElementById(content.id)
        ?.append {
            ol {
                products.forEach {
                    this.li {
                        +it.name
                    }
                }
            }
        }
}

但是我在浏览器控制台中收到错误:

Uncaught (in promise) TypeError:closure$products.iterator is not a function

如何迭代集合并在 UL 标签内为传递给函数的每个产品添加 LI 标签?

标签: kotlinkotlin-jskotlinx-html

解决方案


也许,products.forEach您可以使用简单的for (p in products). 所以代码将是:

fun showProducts(products: List<Product>) {
    document.getElementById(content.id)
        ?.append {
            ol {
                for (p in products) {
                    li {
                        +p.name
                    }
                }
            }
        }
}

看到这个链接: https ://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/Task.kt


推荐阅读