首页 > 解决方案 > 如何使用 Jquery 使按钮将图像与另一个图像交换?

问题描述

我对 Jquery 很陌生,正在尝试学习它,我的代码似乎有问题,我希望它在单击按钮时更改图像,但图像没有改变。

<!DOCTYPE html>
<html>

<head>
  <script src="jquery-3.3.1.min.js">
    $('input').toggle(
      function() {
        $('img').attr('src', '/images/test1.png');
      },
      function() {
        $('img').attr('src', '/images/test2.png');
      }
    );
  </script>
</head>

<body>
  <input value="change image" type="button" />
  <img src="test1.png" />
</body>

</html>

标签: jqueryhtml

解决方案


问题 1

脚本元素加载单个脚本

这可以来自开始标记和结束标记之间的代码src属性指定的 URL 。

它不能同时加载两者。

如果您同时提供两者(正如您所做的那样),src则将使用该属性并且将忽略内联脚本。

您需要两个脚本元素。一个加载 jQuery 库,一个加载使用该库的脚本。

问题 2

脚本运行时input,您的文档中没有任何元素。请参阅为什么 jQuery 或诸如 getElementById 之类的 DOM 方法找不到元素?


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(function() {
    $('input').toggle(
      function() {
        $('img').attr('src', 'https://placeimg.com/150/150/animals');
      },
      function() {
        $('img').attr('src', 'https://placeimg.com/150/150/people');
      }
    );
  });
</script>
<input value="change image" type="button" />
<img src="https://placeimg.com/150/150/animals" />


问题 3

这看起来不像您想要的行为(每次单击某些东西时,切换不会在两个函数之间切换),您可能希望改用单击事件处理程序。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(function() {
    const one = 'https://placeimg.com/150/150/animals';
    const two = 'https://placeimg.com/150/150/people';

    $('input').on('click', toggle);

    function toggle() {
      const current = $('img').attr('src');
      $('img').attr('src', current === one ? two : one);
    }
  });
</script>
<input value="change image" type="button" />
<img src="https://placeimg.com/150/150/animals" />


推荐阅读