首页 > 解决方案 > 我的脚本中有什么错误阻止我的按钮在图像前后插入文本?

问题描述

<!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>

使用上面的代码,我正在做一个使用 jQuery 向我的代码中的图像添加元素的示例。当用户单击“Insert Before”按钮和“Insert After”按钮时,应该分别在我的图像之前和之后插入文本。但是,单击按钮后,不会返回任何内容。我的代码中有什么错误?

标签: jquery

解决方案


推荐阅读