1

如何使当前时间出现在警报框中?我是编程新手,所以我完全迷路了。我正在用 html5 或 javascript 编码。我在这里添加了大部分代码。

这是我的代码:

<script>
    function startTime(){
        var today=Date();
        var h=today.getHours();
        var m=today.getMinutes();
        var s=today.getSeconds(); 
        document.getElementById('txt').innerHTML=h+":"+m+":"+s; 
    }

</script>
<div id="txt"></div>

<h1>What would you like it to say?</h1>

    <p>Commmon Requests:</p>

    <form action="">
    <select name="requests" onchange ="checkIfOther();" id="dropDown1">
    <option value="blank"> </option>
    <option value="good morning sir">Good Morning Sir</option>
    <option value="current time">Current Time</option>
    <option value="other">Other</option>    
    </select>
    </form>

    </p>
<button onclick="mySubmit()" value>Submit</button>

    <div id="other" style="display:none">
        <br><br><label>Optional Request: </label><input type="text" id="otherText"/>
    </div>

</body>
</html>

<script>
    function checkIfOther(){
        a=document.getElementById("dropDown1");        
        if(a.value == "other"){           
            document.getElementById("other").setAttribute("style","display:inline");
        }
        else{
            document.getElementById("other").setAttribute("style","display:none");
            }
    }   
</script>

<script type="text/javascript">
    function mySubmit(){
        var x=document.getElementById("dropDown1");
        if(x.value == "other"){
            alert("You have chosen: " + otherText.value); 
        }
        else if(x.value == "current time"){
            alert("The current time is: " + 'txt'.value); //what do I do here?
        }
        else{   
            alert("You have chosen: " + x.options[x.selectedIndex].text);
        }   
    }   
</script>

难道我做错了什么?

4

3 回答 3

2

首先,您的 HTML 完全搞砸了。验证它。

至于代码本身,startTime是坏的。它需要new Date().

function startTime(){
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds(); 
  return [ h, m, s ].join(':')
}

并将其放入警报框中,您可以这样做:

alert(startTime());

如果你想把它放在一个元素中,<div id="txt"></div>你可以这样做:

document.getElementById('txt').innerHTML = startTime();
于 2013-07-04T12:18:51.140 回答
0

你可以做这样的事情。

...
else if(x.value == "current time"){
    startTime();
    alert("The current time is: " + document.getElementById('txt').innerHTML);
...
于 2013-07-04T12:12:12.490 回答
0

创建一个返回当前时间字符串的函数getTime

function getTime(){
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds(); 
    return h+":"+m+":"+s; 
}

然后使用它:

…
else if(x.value == "current time"){
    alert("The current time is: " + getTime());
}
…

如果您仍然需要该startTime功能,您也可以在那里使用它:

function startTime() {
    document.getElementById('txt').innerHTML = getTime();
}
于 2013-07-04T12:22:35.677 回答