<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function () { var btn = document.querySelector("button:nth-child(1)"); btn.onclick = function() { alert("555"); } } </script> </head> <body> <button>按钮1</button> <button>按钮2</button> <button>按钮3</button> </body> 为什么没反应内容:代码中的错误是在选择器中的拼写错误。应该是nth-child而不是nth.child。 修改后的代码如下: html&#x20;&#x3C;head&#x3E;&#x20;&#x3C;meta&#x20;charset&#x3D;&#x22;UTF-8&#x22;&#x3E;&#x20;&#x3C;meta&#x20;http-equiv&#x3D;&#x22;X-UA-Compatible&#x22;&#x20;content&#x3D;&#x22;IE&#x3D;edge&#x22;&#x3E;&#x20;&#x3C;meta&#x20;name&#x3D;&#x22;viewport&#x22;&#x20;content&#x3D;&#x22;width&#x3D;device-width,&#x20;initial-scale&#x3D;1.0&#x22;&#x3E;&#x20;&#x3C;title&#x3E;Document&#x3C;/title&#x3E;&#x20;&#x3C;script&#x3E;&#x20;window.onload&#x20;&#x3D;&#x20;function&#x20;()&#x20;{&#x20;var&#x20;btn&#x20;&#x3D;&#x20;document.querySelector(&#x22;button:nth-child(1)&#x22;);&#x20;btn.onclick&#x20;&#x3D;&#x20;function()&#x20;{&#x20;alert(&#x22;555&#x22;);&#x20;}&#x20;}&#x20;&#x3C;/script&#x3E;&#x20;&#x3C;/head&#x3E;&#x20;&#x3C;body&#x3E;&#x20;&#x3C;button&#x3E;按钮1&#x3C;/button&#x3E;&#x20;&#x3C;button&#x3E;按钮2&#x3C;/button&#x3E;&#x20;&#x3C;button&#x3E;按钮3&#x3C;/button&#x3E;&#x20;&#x3C;/body&#x3E;&#x20; 修改后的代码中,选择器button:nth-child(1)将选择第一个button元素。然后,将为该按钮添加onclick事件,当点击按钮时,弹出一个包含文本555的警告框。 请确保将代码正确地复制并粘贴到您的HTML文件中,并确保在浏览器中正确加载该文件。

JavaScript 选择器错误:nth-child vs nth.child | 代码调试技巧

原文地址: https://www.cveoy.top/t/topic/qdV1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录