JavaScript按钮无法加载产品信息,请求排查body代码问题
按钮点击无响应的问题排查与修复
核心错误点及修复方案
- 构造函数方法挂载错误:你定义的
writegameProducts函数没有绑定到gameProducts构造函数的原型上,导致实例(Nintendo、PlayStation等)无法调用该方法。需将方法添加到构造函数的原型链中。 - 函数名拼写不一致:Steam按钮的
onclick事件里写的是writeGameProducts()(G大写),但实际方法名是writegameProducts(G小写),大小写不匹配导致调用失败。 - 缺少内容展示容器:
writeText函数需要向id为products的元素写入内容,但你的HTML中没有这个元素,导致内容无法显示。 - 无效HTML结构:用
<button>嵌套<input type="button">不符合规范,会导致按钮行为异常,需移除外层<button>标签。 - name属性无需调整:你怀疑的name属性和按钮功能无关,不影响方法调用,无需修改。
修复后的完整代码
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>Module 7</title> <link rel="stylesheet" type="text/css" href="style7.css"> <header> <img src="goose.png" height="190" width="190"><p>Space Goose Gaming Depot</p> </header> <script type="text/javascript"> /* 构造函数:游戏产品信息 */ function gameProducts (gamingsystem, gamegenre, gameaccessory){ this.console = gamingsystem; this.genre = gamegenre; this.accessory = gameaccessory; } /* 将方法挂载到构造函数原型,让所有实例都能调用 */ gameProducts.prototype.writegameProducts = function (){ var str = "Are you interested in purchasing a " + this.console + " ? " + "Look no further, we feature a wide range of their latest and vintage products. Stop by to purchase or trade in a video game. If you trade in a video game, you can get a 20% discount on the purchase of their newest game, " +this.genre+ ". We are also offering 45% your entire purchase if you buy a new " + this.accessory; writeText(str, "products"); } /* 向指定元素写入文本的工具函数 */ function writeText(txt, destination){ document.getElementById(destination).innerHTML=txt; } /* 游戏产品实例 */ var Nintendo = new gameProducts ("Nintendo Switch","Super Mario Party","Nintendo Switch Lite case"); var PlayStation = new gameProducts("PS5","Hogwarts Legacy","DualSense™ Edge Wireless Controller"); var Xbox = new gameProducts("Xbox Series X","NBA 2K23","Gamevice Flex for Android"); var Steam = new gameProducts("Steam Deck","Apex Legends","JSAUX Steam Deck Dock"); </script> </head> <body> <div class="productinfo"> <p>Current Deals and Steals!</p> </div> <!-- 添加内容展示容器 --> <div id="products"></div> <!-- 移除外层button标签,修正Steam按钮的函数名 --> <input type="button" onclick="Nintendo.writegameProducts()" value="Nintendo" name="gameProducts"/> <input type="button" onclick="PlayStation.writegameProducts();" value="PlayStation" name="gameProducts"/> <input type="button" onclick="Xbox.writegameProducts();" value="Xbox" name="gameProducts"/> <input type="button" onclick="Steam.writegameProducts();" value="Steam" name="gameProducts"/> </body> </html>
内容的提问来源于stack exchange,提问作者dry_onion
相关产品推荐
相关产品推荐

