我正在写一个基本上翻转硬币的javascript函数,我试图让它返回图像,但到目前为止还没有运气。我使用img src标签为变量赋值但不知何故我怀疑它不起作用我想和你们一起检查这是如何实际完成的?
这是我的代码:
<script type = text/javascript>
var headsCount = 0;
var tailsCount = 0;
function start()
{
var buttonTwo = document.getElementById("coinButton");
buttonTwo.addEventListener("click", coinResult, false);
}
function flip()
{
var faceValue = Math.floor((Math.random()*2)+1);
if (faceValue == 1)
{
headsCount++;
return true;
}
else
{
tailsCount++;
return false;
}
}
function coinResult()
{
var result = document.getElementById("coinToss");
var coinCount = document.getElementById("countNumber");
<img name = "Heads" src = "images/Heads.png" />
if (flip() == true)
{
result.innerHTML = <img src = "images/Heads.png" alt = "Heads" />
}
else
{
result.innerHTML = <img src = "images/Tails.png" alt = "Tails" />
}
coinCount.innerHTML = "Heads Count: " + headsCount + " Tails Count: " + tailsCount;
}
window.addEventListener("load", start, false);
</script>
答案 0 :(得分:3)
innerHTML属性必须接收代表你的html的字符串,所以:
result.innerHTML = "<img src='images/heads.png' alt='heads' />";
如果你想在你的html中使用引号而不是单引号(是的,你可以,有些人更喜欢它),你必须转义引号(通过在它之前添加反斜杠),以便javascript引擎可以理解引号是文本,不标记字符串的开头或结尾,如:
result.innerHTML = "<img src=\"images/heads.png\" alt=\"heads\" />";
PS:我正在考虑将你的coinToss元素作为div。
答案 1 :(得分:-2)
结果行当然需要引号“和”,并通过/
转义result.innerHTML = "<img src = 'images/\Heads.png' alt = 'Heads' />"
或使用.src和.alt来重新加载img:
<html>
<head>
<script type=text/javascript>
function addEventtoButton(){
var element = document.getElementById('testing');
element.onclick = function coinResult () {
var a;
a = document.getElementById("coin");
if (false) { // or set if to true, or flip() as in original example
a.src='images/\Heads.png';
a.alt='Heads';
} else {
a.src='images/\Tails.png';
a.alt='Tails';
} };
}
</script>
</head>
<body onload='addEventtoButton()'>
<button id='testing'>testme</button>
<img name='coin' id='coin' src='images\Heads.jpg'>
</body>
</html>