PyScript按钮禁用功能失效求助:点击按钮无法禁用另一按钮
解决点击按钮禁用另一个按钮的问题
你当前代码的核心问题是错误地把disabled当成CSS样式属性来设置,实际上它是HTML按钮的原生布尔属性,因此用setAttribute("style", "disabled:True")根本无法实现禁用效果。
修正方案:
- 禁用按钮:直接操作按钮元素的
disabled属性,或者使用setAttribute设置disabled属性(布尔属性只要存在就生效,无需赋值True)。 - 修改按钮颜色:建议直接操作
style对象的对应属性,避免覆盖原有样式。
修正后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://pyscript.net/releases/2023.11.1/core.css" /> <script type="module" src="https://pyscript.net/releases/2023.11.1/core.js"></script> </head> <body> <div> <button id="run" py-click="colorChange">NO CLICK</button> <button id="run2" py-click="disableRunButton">CLICK</button> </div> <style> #run{ background-color: rgb(61, 139, 130)} #run2{ background-color: rgb(179, 28, 65)} </style> <py-script> from js import document runButton = document.getElementById("run") def colorChange(event): # 直接修改style属性,不覆盖原有样式 runButton.style.backgroundColor = "red" def disableRunButton(event): # 方式1:直接设置disabled属性 runButton.disabled = True # 方式2:用setAttribute设置(二选一即可) # runButton.setAttribute("disabled", "") </py-script> </body> </html>
额外说明:
- 把原函数名
disabled改成了disableRunButton,避免和属性名混淆,代码更清晰。 - 如果需要重新启用按钮,只需设置
runButton.disabled = False或者runButton.removeAttribute("disabled")。
内容的提问来源于stack exchange,提问作者Joselu
相关产品推荐
相关产品推荐

