首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

jQuery html()方法:傳函數引用vs調用函數的本質區別

     編輯:程式設計疑難解答

現場代碼

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);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved