onclick更改图像并打开网址

时间:2017-01-16 17:37:57

标签: javascript image onclick

我需要在点击图片时更改图片并加载网址而页面上没有任何视觉上的变化。我只需要两个图像,每个图像将与一个URL相关联。我能够复制位于以下位置的onclick图像更改示例: http://www.paulgriffiths.net/program/javascript/otherbasic1.php

例如:我希望地球的图像变为火星并加载URL#1。然后当点击火星时我希望它加载回地球的图片并加载URL#2。我希望URL在后台加载,而不是更改地球和火星的图像。

我将如何添加到" .js"下面的文件来完成这个?

var newsrc = "mars.jpg";

function changeImage() {
  if ( newsrc == "mars.jpg" ) {
    document.images["pic"].src = "/images/program/js/forms/mars.jpg";
    document.images["pic"].alt = "Mars";
    newsrc  = "earth.jpg";
  }
  else {
    document.images["pic"].src = "/images/program/js/forms/earth.jpg";
    document.images["pic"].alt = "Earth";
    newsrc  = "mars.jpg";
  }
}

1 个答案:

答案 0 :(得分:0)

我使用布尔值而不是测试字符串,但这应该可以帮到你。

function loadCommand(url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // if successfull
    } else {
      // if not successfull
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

var isOn = false;
var img = document.getElementById("pic");

// change handler
var loadImage = function() {
    if (isOn) {
        loadCommand("http://x.x.x.x/cmd/DOFF");
        img.src = "/images/program/js/forms/mars.jpg";
        img.alt = "Mars";
    } else {
        loadCommand("http://x.x.x.x/cmd/DON");
        img.src = "/images/program/js/forms/earth.jpg";
        img.alt = "Earth";
    }

};

// set up event handler
img.onclick = function() {
    // potentially send window to new location with window.location=<host>/cmd/DOFF or something similar
    // or just change state
    isOn = !isOn;

    loadImage();
};

// load initial image
loadImage();