javascript - 用 1 行代码在 Javascript 中显示实时日期 + 时间

标签 javascript jquery date time

我运行了这个命令

$("#dateTime").text(new Date().toLocaleString());

我看到这个,2/21/2020, 10:29:14 AM

我希望每秒增加时间,所以我尝试了

setInterval($("#dateTime").text(new Date().toLocaleString()), 1000);

我不断得到

VM1104:1 Uncaught SyntaxError: Unexpected identifier

最佳答案

$("#dateTime").text(new Date().toLocaleString() 包装在函数中。setInterval function Expect function 作为第一个参数。

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval(). This method is defined by the WindowOrWorkerGlobalScope mixin.

var intervalID = scope.setInterval(func, delay);

参数

func: A function to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.

code: An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using eval() a security risk.

delay: The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See Delay restrictions below for details on the permitted range of delay values.

工作示例

setInterval(() => $("#dateTime").text(new Date().toLocaleString()), 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dateTime"></div>

您可以阅读有关 setInterval here 的更多信息

关于javascript - 用 1 行代码在 Javascript 中显示实时日期 + 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60341878/

相关文章:

javascript - jQuery Mobile 中的空控制组

javascript - jQuery 验证 : how to make the amount of characters no include the tokens generated by CKEditor?

excel - 如何在 Excel 中获取显示值而不是实际值?

php - 在 php 中将 DateInterval 对象转换为秒数

date - Excel 编写器日期格式错误

javascript - token 刷新后 Angular 4 拦截器重试请求

javascript - 为什么我的 JavaScript 不被认为是安全的?

javascript - 禁用页面中的所有 kendoui 元素

jQuery on mouseover 在 mouseout 恢复时做一些事情

javascript - 嵌套 Handlebars 'lookup' 与 'if'