首页 > 解决方案 > 如何在javascript中获取图像的src

问题描述

rpsFrontEnd()我一直从变量的函数中取回“图像未定义”,humanImageChoice尽管我曾经使用 this过参考用户的输入。需要你的帮助。

function rpsGame(yourChoice) {
  console.log(yourChoice);
  var humanChoice, botChoice;
  humanChoice = yourChoice.id;

  botChoice = numberToChoice(randToRpsInt(randToRpsInt));
  console.log('Computer Choice:' + botChoice);

  result = decideWinner(humanChoice, botChoice); //[0,1] human lost 
  console.log(result);

  message = finalMessage(result); //you won
  console.log(message);

  rpsFrontEnd(yourChoice, botChoice, message);
}

function rpsFrontEnd(humanImageChoice, botImageChoice, message) {
  var imageDatabase = {
    'rock': document.getElementById('rock').src,
    'paper': document.getElementById('paper').src,
    'scissors': document.getElementById('scissors').src
  }
  //removing the images onclicking an image
  document.getElementById('rock').remove();
  document.getElementById('paper').remove();
  document.getElementById('scissors').remove();

  //creatin divs for the image choices to be placed in

  var humanDiv = document.createElement('div');
  var botDiv = document.createElement('div');
  var messageDiv = document.createElement('div');

  humanDiv.innerHTML = "<img src='" + imageDatabase[humanImageChoice] + "'>"
  document.getElementById('flex-box-rps-div').appendChild(humanDiv);
}
<div class="container-3">
  <h2>Challenge 3: Rock paper Scissors</h2>
  <div class="flex-box-rps" id="flex-box-rps-div">
    <img id="rock" src="static/imgs/rock.jpg" height="150px" width=" 150px" onclick="rpsGame(this)" />
    <img id="paper" src="static/imgs/paper.jpg" height="150px" width=" 
        150px" onclick="rpsGame(this)" />
    <img id="scissors" src="static/imgs/scissors.jpg" height="150px" width=" 
                  150px" onclick="rpsGame(this)" />
  </div>
</div>

标签: javascript

解决方案


图像 src 不正确。它将在rpsFrontEnd功能上,

humanDiv.innerHTML = "<img src='" + imageDatabase[humanImageChoice.src] + "'>"

或者在rpsGame功能上,

 yourChoice.src

如果这不能解决问题,请检查您的浏览器控制台。也许它会为其他功能带来另一个错误。


推荐阅读