function current() {
var d = new Date(), str = '';
str += d.getFullYear() + '年';
str += d.getMonth() + 1 + '月';
str += d.getDate() + '日';
str += d.getHours() + '時';
str += d.getMinutes() + '分';
str += d.getSeconds() + '秒';
return str;
}
setInterval(function() {
$("#nowTime").html(current); // 傳函數引用
// $("#nowTime").html(current()); // 調用函數
}, 1000);
| 寫法 | 本質 | 執行時機 | 結果 |
|---|---|---|---|
.html(current) | 傳遞函數對象 | jQuery內部每次調用該函數 | ✅ 每秒更新時間 |
.html(current()) | 傳遞函數返回值 | 僅在setInterval回調執行時調用一次 | ❌ 靜態時間字符串 |
jQuery .html() 方法簽名:
.html( htmlString )
.html( function(index, oldhtml) { return newHtml; } )
當傳入函數時,jQuery會為匹配的每個元素調用該函數,將返回值作為新HTML內容。因此:
current:每秒調用一次,返回最新時間字符串 ✅current():立即執行返回固定字符串,後續每秒重複設置同一字符串 ❌若在$.ajax回調中使用window.open,因瀏覽器攔截策略,異步回調中打開的窗口會被攔截。解決方案:
async: false,不推薦)location.href// 推薦:箭頭函數簡潔明確
setInterval(() => $("#nowTime").html(current()), 1000);
// 或:直接調用
setInterval(function() {
$("#nowTime").html(current());
}, 1000);