【问题标题】:Build HTML by iteration with kotlinx.html使用 kotlinx.html 通过迭代构建 HTML
【发布时间】:2020-02-03 17:35:56
【问题描述】:

我正在尝试通过迭代集合来使用 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 标签?

【问题讨论】:

标签: kotlin kotlin-js kotlinx-html


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多