![](/img/trans.png)
[英]If I type "hello" into a text box, how can I make an alert appear by pressing a button?
[英]How to make the current time appear in an alert box
如何使当前时间显示在警报框中? 我是编程的新手,所以我完全迷路了。 我正在用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>
难道我做错了什么?
首先,您的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();
你可以做这样的事情。
...
else if(x.value == "current time"){
startTime();
alert("The current time is: " + document.getElementById('txt').innerHTML);
...
使函数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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.