首页 > web前端 > js教程 > 正文

如何在JavaScript / jQuery中更改img元素的src属性?

WBOY
发布: 2023-08-23 16:49:14
转载
2625 人浏览过

使用JavaScript和jQuery,有不同的方法来更改在HTML文档中给出的如何在JavaScript / jQuery中更改img元素的src属性?元素的src属性的图像路径。

使用JavaScript更改img元素的src属性的方法−

  • 使用JavaScript中的src属性。

使用jQuery更改img元素的src属性的方法−

  • 使用 attr() 方法

  • 使用prop()方法

让我们逐一详细讨论上述列出的更改img元素src的方法。

在JavaScript中使用src属性

JavaScript允许我们使用src属性来获取已经分配给它的值,同时也可以更新或更改相同属性的值。这是一种非常常见的更改img元素的src属性值的方法。

Syntax

以下语法将向您解释如何在JavaScript中使用src属性来更改img元素的src属性的值 -

Selected_image_element.src = " new value ";
登录后复制

让我们通过代码示例来理解这种方法的实际实现。

算法

  • Step 1 − In the first step, we will add a img element with a src attribute associated with it, whose value we will change later using the src property in JavaScript.

  • 第二步 - 在这一步中,我们将添加一个带有onclick事件的按钮元素,当用户点击按钮时调用一个函数来改变图像的src。

  • 步骤 3 - 在下一步中,我们将定义一个 JavaScript 函数,在该函数中,我们将使用其 ID 获取 img 元素,然后使用 src 属性更改 src 属性,并在两个图像之间切换。

  • Step 4 − In the last step, we will assign the function to the onclick event defined in the last step to see the changes on user screen.

Example

的中文翻译为:

示例

下面的示例将向您解释如何在JavaScript中实际使用src属性来更改img的src属性。

<html>
<body>
   <h2>Change the src attribute of an img element</h2>
   <p id = "upper">The image shown below will be changed once you click the button.</p>
   <img src =  "https://img.php.cn/" id = "image"> <br> <br>
   <button id = "btn" onclick = "changeSrc()">Click to change the Image</button>
   <p id = "result"> </p>
   <script>
      var result = document.getElementById("result");
      var upper = document.getElementById("upper");
      function changeSrc() {
         var img = document.getElementById('image');
         if (img.src == "https://img.php.cn/") {
            img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoLnvRnTNP2rojd7e9b_Ilw5zZkSlPotSPIA&usqp=CAU";
            result.innerHTML += " The src of above img is changed from <b> Link 1 </b> to " + " <b> Link 2 </b> <br>";
         }
         else {
            img.src = "https://img.php.cn/";
            result.innerHTML += " The src of above img is changed from <b> Link 2 </b> to " + " <b> Link 1 </b> <br>";
         }
         upper.innerHTML = " The image shown previously is replaced by some other image as <b> src attribute of img is changed. </b> <br> ";
      }
   </script>
</body>
</html>
登录后复制

在这个示例中,我们使用JavaScript中的src属性来改变HTML文档中img元素的src属性。在这里,每次点击按钮时,我们在两个图像之间切换。

在jQuery中使用attr()方法

我们还可以使用JavaScript中的attr()方法来更改src属性。

attr()方法 - attr()方法接受两个参数,第一个参数是要更改的属性名称,以字符串形式表示,另一个参数是要分配给属性的新值。

Syntax

以下语法将向您解释带有参数的attr()方法的实现方式−

attr(" attribute_name ", " new_value ");
登录后复制

让我们通过代码示例详细了解这种方法的实现。

算法

  • 第一步 - 在文档的元素中的

    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!