0

我正在编写一个基本上翻转硬币的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>
4

2 回答 2

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。

于 2013-02-14T15:08:07.453 回答
-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>
于 2013-08-10T18:22:44.010 回答