我的jQuery脚本存在什么错误导致按钮无法在图片前后插入文本?
错误原因
代码的核心问题是jQuery方法的调用语法错误:before和after是jQuery提供的DOM操作方法,需要用圆括号()传入参数执行,你错误使用了方括号[],相当于尝试读取jQuery对象上名为Before/After的属性,没有实际执行插入逻辑,因此点击按钮后页面没有响应。
修正方案
将script标签内的两行错误代码:
$("img").before["Before"]; $("img").after["After"];
替换为正确的方法调用写法:
$("img").before("Before"); $("img").after("After");
完整修正后代码
<!DOCTYPE html> <html lang="en"> <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>Add Elements</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function () { $(".test").click(function () { $("img").before("Before"); }); $(".test2").click(function () { $("img").after("After"); }); }); </script> </head> <body> <h3>Example:</h3> <p> Text will be inserted before and after the selected HTML element (img) upon clicking the respective buttons. </p> <img src="https://forums.homecomingservers.com/uploads/monthly_2020_10/2400px-Issue27-fullsize.png.b4bbd047f7804c86e1b10df2b90ac37c.png" alt="Issue 27" style="width: 500px" /> <br /> <button class="test">Insert Before</button> <button class="test2">Insert After</button> </body> </html>
内容的提问来源于stack exchange,提问作者Jermal
相关产品推荐
相关产品推荐

