gpt4 book ai didi

javascript - 带有时间的 html/javascript onclick 函数

转载 作者:行者123 更新时间:2023-11-30 14:07:36 25 4
gpt4 key购买 nike

我希望在单击我的标签时执行一个 javascript 函数,该函数将返回该单击的确切时间,包括小时、分钟和秒。我有一个 javascript 函数可以执行我想要的操作,但是当我单击标签时,什么也没有出现。我做错了什么吗?

function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
return timeString;
}

const hoursSpan = document.getElementById('hours');
hoursSpan.textContent = getTime();
<div class="wrap-input100 rs1-wrap-input100 validate-input">
<span class="label-input100">Date</span>
<input class="input100" onclick="getTime()" id="hours" name="Date" placeholder="Date">
<span class="focus-input100"></span>
</div>

最佳答案

<input>元素没有 textContent你应该改变value .设置你的onclick另一个事件function这会改变value每次点击。

您还可以在 getTime() 中添加以下行摆脱其他changeTime()

hoursSpan.textContent = getTime();

const hoursSpan = document.getElementById('hours');
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
return timeString;
}

function changeTime(){
hoursSpan.value = getTime();
}
<div class="wrap-input100 rs1-wrap-input100 validate-input">
<span class="label-input100">Date</span>
<input class="input100" onclick="changeTime()" id="hours" name="Date" placeholder="Date">
<span class="focus-input100"></span>
</div>

关于javascript - 带有时间的 html/javascript onclick 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com