使用PyScript获取HTML输入框值失败,求原因及解决方法
PyScript获取输入框内容返回None的解决办法
问题场景
在HTML项目中使用PyScript开发,预期点击提交按钮后将上方文本替换为输入框的值,但代码仅返回None,无法获取输入框内容。
原HTML代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>PyScript Template</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-env> - paths: - /demo.py </py-env> </head> <body style="font-family:Times New Roman;margin-left:40px"> <br> <p id=main_description class=text> Hello, world. </p> <input class=player_input type=text id=input_box name=input autocomplete=off placeholder="What will you do?"> <button type=button id=submit pys-onclick=submit_input>submit</button> <py-script src=/demo.py></py-script> </body> </html>
原PyScript代码:
# demo.py def submit_input(e): input_box = Element("input_box") player_input = input_box.select(".value") main_description = Element("main_description") main_description.write(player_input)
问题原因
错误使用了select(".value")方法获取输入框值:PyScript的Element对象中,select()方法用于选择当前元素下的子元素,而非获取表单元素的输入值,因此返回None。对于输入框这类表单元素,需直接访问.value属性来获取内容。
修正后的代码
修改demo.py中的逻辑,直接通过.value属性获取输入框内容:
# demo.py def submit_input(e): input_box = Element("input_box") # 直接访问.value属性获取输入框的文本内容 player_input = input_box.value main_description = Element("main_description") main_description.write(player_input)
说明
- 通过
Element("input_box")获取输入框对应的PyScript Element对象 - 访问该对象的
.value属性,即可得到用户在输入框中输入的文本 - 最后调用
main_description.write(player_input),将输入内容写入目标<p>标签,完成文本替换
内容的提问来源于stack exchange,提问作者Dominic Miller
相关产品推荐
相关产品推荐

