我想运行一个函数来记录表的每一行。我想在HTML代码加载后做,我尝试这个
<body>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/pyodide/dev/full/pyodide.js"
></script>
<script type="text/javascript">
async function main(kw) {
let pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/dev/full/",
});
pyodide.globals.set("mikw", kw);
await pyodide.loadPackage("micropip");
await pyodide.runPythonAsync(`
import micropip
import js
await micropip.install('snowballstemmer')
import snowballstemmer
stemmer = snowballstemmer.stemmer('english')
div = js.document.createElement("div")
div.innerHTML = stemmer.stemWords('Hello this my default text '.split())
js.document.body.prepend(div)
varP = js.document.getElementById('origen').textContent
print(varP)
salida = stemmer.stemWords(varP.split())
print(salida)
divSalida = js.document.createElement("div")
div.innerHTML =salida
salida = stemmer.stemWords(mikw.split())
print(salida)
`);
}
main('This are the second text, I put this text on arguments function');
</script>
<div id="origen" >This text is inside of HTML element</div>
</body>
输出为
['This', 'text', 'is', 'insid', 'of', 'HTML', 'element']
['This', 'are', 'the', 'second', 'text,', 'I', 'put', 'this', 'text', 'on', 'argument', 'function']
但我不能(或我不知道)使用函数来系统其他知识后加载html,例如加载DOM后(获取我的html表的值并运行每个)
....
<div id="origen" onclick="temp()">This text is inside of HTML element</div>
<script>
myNewkwStemm=main('other word');
myNewkwStemm2=main('word2');
</script>
</body>
通过在main函数中包含loadPyodide
调用来多次加载Pyodide,这会为后续的main
调用提供错误。将loadPyodide
移出main
应能解决问题:
<script type="text/javascript">
let initPyodide = loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/dev/full/",
})
async function main(kw) {
let pyodide = await initPyodide
// ... other code
}
jsfiddle
你也可能不想依靠pyodide.globals
来传递参数,因为它会导致竞争条件,因为你正在异步运行一切。