如何让当前时间出现在警告框中?我是编程的新手,所以我完全迷失了。我用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>
我做错了吗?
答案 0 :(得分: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();
答案 1 :(得分:0)
你可以这样做。
...
else if(x.value == "current time"){
startTime();
alert("The current time is: " + document.getElementById('txt').innerHTML);
...
答案 2 :(得分: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();
}