使用javascript在网页中设置不同的src图片

时间:2019-02-04 03:59:29

标签: javascript html

我正在尝试使用标签buttononclick属性来更改网页中的图片,这些标签调用了我在js文档中所做的函数,但是它不起作用,这是做什么的?

在Javascript中:

function store (a,z) {
  var pic;
  if (a>z) {
       pic = "images_weddings/desing_logo-01.jpg";
  }else{
       pic = "images_weddings/rose1.jpg";
  }
  document.getElementById('change1').src = pic;
}

和html中的

      矩阵

  <div>
      <img src="images_weddings/desing_logo-01.png" id="change1" >
  </div>

  <button type="button" onclick="store(2,3)">change the image</button>

2 个答案:

答案 0 :(得分:0)

我更改了图像的链接,并且代码工作正常-您的代码中的奇怪之处在于,在html中,您有PNG文件“ desing_logo-01.png”,而在js中,您有JPG文件“ desing_logo-01.jpg”

function store (a,z) {
  var pic;
  if (a>z) {
       pic = "https://i.ytimg.com/vi/ktlQrO2Sifg/maxresdefault.jpg";
  }else{
       pic = "https://thechive.files.wordpress.com/2018/03/girls-whose-hotness-just-trumped-cute-89-photos-257.jpg?quality=85&strip=info&w=600";
  }
  document.getElementById('change1').src = pic;
}
<div>
  <button type="button" onclick="store(2,3)">change the image</button>
  <img src="https://i.ytimg.com/vi/ktlQrO2Sifg/maxresdefault.jpg" id="change1" >
</div>

答案 1 :(得分:0)

在您的小伙伴中尝试此代码

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<title> </title>

</head>
<body>

<div>
      <img src="images_weddings/desing_logo-01.png" id="change1" >
  </div>

  <button type="button" onclick="store(2,3)">change the image</button>

  <script type="text/javascript">

    function store (a,z) {
  var pic;
  if (a>z) {
       pic = "images_weddings/desing_logo-01.png";
  }else{
       pic = "images_weddings/rose1.png";
  }
  document.getElementById('change1').src = pic;
}
  </script>

</body>