attr() 方法

.attr() 方法用于获取匹配集中第一个元素的属性值。
要分别获取每个元素的值,我们可以使用循环结构,例如 .each() 或者 .map() 方法。

如何使用 jQuery 更改图片源

更改图片源的最佳方法可能是使用 jQuery 的 attr() 函数。

例如,假设 <img> 标签的 id 属性为“your-image”,因此我们可以这样做:

<img id="your-image" src="image1.jpg"/>

接下来,我们可以使用 jQuery 更改图像的 src,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src="https://onitroad.com/car.png" alt="JS" />
    </div>
    <script>
      $(document).ready(function() {
          $("img").click(function() {
              //Change src attribute of image
              $("#your-image").attr("src", "https://www.onitroad.com/nature.png");
            });
        });
    </script>
  </body>
</html>

要将代码添加到点击事件,我们可以执行以下操作:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src="https://onitroad.com/car.png" alt="JS" />
    </div>
    <script>
      $(document).ready(function() {
          $('#your-image').on({
              'click': function() {
                $('#your-image').attr('src', "https://www.onitroad.com/nature.png");
              }
            });
        });
    </script>
  </body>
</html>

要更改图像,我们可以执行以下操作:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      img {
        width: 300px;
        height: 200px;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <div class="imgDiv">
      <img id="your-image" src='https://onitroad.com/car.png' alt="Image" />
    </div>
    <script>
      $(document).ready(function() {
          $('img').on({
              'click': function() {
                let src = ($(this).attr('src') === 'https://www.onitroad.com/car.png') ?
                  'https://www.onitroad.com/nature.png' :
                  'https://www.onitroad.com/car.png';
                $(this).attr('src', src);
              }
            });
        });
    </script>
  </body>
</html>
日期:2020-06-02 22:16:08 来源:oir作者:oir