【问题标题】:How to print out Brython.js output as a DOM element into a specific DOM?如何将 Brython.js 输出作为 DOM 元素打印到特定的 DOM 中?
【发布时间】:2021-03-15 06:41:45
【问题描述】:

我正在使用 Brython.js,我可以在 HTML 浏览器中打印一个循环,但正如您所见,这是将输出添加到整个 DOM。

如何将打印结果附加到特定的 DOM 元素中?例如,如果我想将输出打印到#map,我该怎么做?

    <ul id="maps"></ul>
    <script type="text/python">
        from browser import document
        import sys
        sys.stdout = document
        maps= ["world", "asia", "africa"]
        for x in maps:
         print(x)
     </script>

【问题讨论】:

  • 请快速提醒您问题中的恳求程度,Behseini。我最近注意到它hereherehere
  • 值得注意的是,那些觉得自己被高举、被捧上神坛或被讨好的读者可能会决定跳过这个问题。大多数人宁愿被当作同事来交谈——也许是因为乞讨可以被解释为一种情绪操纵的形式。

标签: python brython


【解决方案1】:

您可以将自定义类的实例分配给sys.stdout。你只需要重写 write 方法。例如:

from browser import document
import sys

class CustomStdout:
    def write(self, txt):
        document['maps'].html += f'<li>{txt}</li>'


sys.stdout = CustomStdout()

maps = ["world", "asia", "africa"]

for x in maps:
    print(x)

但以下会更简单:

from browser import document
from browser.html import LI

maps_ul = document['maps']
maps = ["world", "asia", "africa"]

for x in maps:
    maps_ul <= LI(x)

&lt;= 运算符是 DOMElement 类型的操作数,其作用类似于 brython 中的 appendChild

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多