JavaScript自动更改img src

时间:2015-02-17 15:27:06

标签: javascript prompt

问题

我几乎完成了我的项目,但我还有另一个问题,我无法弄明白。当提示框关闭时,我需要自动更改图像src。这就是我的意思。

实施例

假设我有这段代码。

HTML

<button id="begin" onClick="javascript:fight();">Begin</button>
<img id="scenario" src="http://www.thegaminghideout.com/school/stage1.png">

JAVASCRIPT

function fight()  {
  var img = document.getElementById("scenario");
  var start = document.getElementById("begin");
  img.src = "http://www.thegaminghideout.com/school/map.jpg"; /* This changes it when the function is called */
  var decision1 = function()  {
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if(decision === "ATTACK")  {
      attack();
    }
    if(decision === "SLEEP")  {
      sleep();
    }
    if(decision === "PASS")  {
      skip();
    }
  }

问题

当(提示)对话框关闭时,如何自动更改img的src?或者,检查它是否打开?

我尝试了什么

  • img.src = "http://www.thegaminghideout.com/school/stage1.png";放在后面 fight()功能
  • 尝试这样的支票:if(fight() === true) { img.src =
    "http://www.thegaminghideout.com/school/stage1.png"; }
  • 添加&#39;刷新&#39;功能,但它破坏了代码。

注意事项

  • 我知道我的示例中的JavaScript可能看起来不对, 因为我的语法错误或者没有attack()sleep()或者 skip()功能。嗯,这只是一个例子,所以我没有张贴 我的整个游戏代码,大约1000行。
  • 我将使用上面提供的代码和JSFiddle发布一个代码段 与实际项目的完整代码更好 故障排除。

&#13;
&#13;
function fight() {
  var img = document.getElementById("scenario");
  var start = document.getElementById("begin");
  img.src = "http://www.thegaminghideout.com/school/map.jpg"; /* This changes it when the function is called */
  decision1();
  var decision1 = function() {
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if (decision === "ATTACK") {
      attack();
    }
    if (decision === "SLEEP") {
      sleep();
    }
    if (decision === "PASS") {
      skip();
    }
  }
}
&#13;
<img id="scenario" src="http://www.thegaminghideout.com/school/stage1.png">
<button id="begin" onClick="javascript:fight();">Test</button>
&#13;
&#13;
&#13;

http://jsfiddle.net/d8sxxykj/

2 个答案:

答案 0 :(得分:3)

function fight()  {

  var start = document.getElementById("begin");
  var decision1 = function()  {
    var img = document.getElementById("scenario");
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if(decision === "ATTACK")  {
    img.src = "http://www.thegaminghideout.com/school/map.jpg";
    attack();
    }
    if(decision === "SLEEP")  {
    img.src = "something.jpg";
    sleep();
    }
    if(decision === "PASS")  {
    img.src = "something.jpg";
    skip();
    }
}  

答案 1 :(得分:0)

尝试,

$("#scenario").attr("src", "http://www.thegaminghideout.com/school/stage1.png");

而不是

img.src = "http://www.thegaminghideout.com/school/stage1.png";

希望它有所帮助!