我有一个js互操作函数,它使用for in构造来迭代输入元素,但它在运行时抛出了错误。
native("document")
val ndoc: dynamic = noImpl
fun jsInterOp() {
js("console.log('JS inling from kotlin')")
val ies = ndoc.getElementsByTagName("input")
for (e in ies) {
console.log("Input element ID: ${e.id}")
}
}获取以下js错误
Uncaught TypeError: r.iterator is not a functionKotlin.defineRootPackage.kotlin.Kotlin.definePackage.js.Kotlin.definePackage.iterator_s8jyvl$ @ kotlin.js:2538对如何修复这个问题有什么建议吗?
Kotlin : M12
为该函数生成的js代码是,
jsInterOp: function () {
var tmp$0;
console.log('JS inling from kotlin');
var ies = document.getElementsByTagName('input');
tmp$0 = Kotlin.modules['stdlib'].kotlin.js.iterator_s8jyvl$(ies);
while (tmp$0.hasNext()) {
var e = tmp$0.next();
console.log('Input element ID: ' + e.id);
}
},发布于 2015-06-21 16:55:44
forEach不起作用,因为它是JS中的Array函数,但getElementsByTagName返回HTMLCollection。因此,我更改了kotlin代码,以使用传统的for循环,该循环遍历此集合并按预期工作。
val ies = ndoc.getElementsByTagName("input")
for (i in 0..(ies.length as Int) - 1) {
console.log("InputElement-${i} : ${ies[i].id}")
}发布于 2015-06-21 03:04:36
Kotlin for-loop使用了很多内部魔法,forEach()在JS上更简单。试试这个:
ies.iterator().forEach { ... }这似乎是Kotlin M12中的一个错误,因为我甚至无法对简单的列表执行for循环。
for(i in listOf(1, 2)); // TranslationInternalException也叫
我不确定您在这里使用document是什么,但您可能会喜欢标准的API:
import kotlin.browser.document
val ies = document.getElementsByTagName("input")https://stackoverflow.com/questions/30947828
复制相似问题