一千萬個為什麽

搜索

關於javascript事件處理程序語法的問題

我的問題似乎在昨天被刪除之前就被刪除了,所以我正在開始一個關於這個主題的新線程。

我一直試圖找到跨瀏覽器調整大小的JavaScript,並在這裏發布的一個答案中遇到了這種語法:

$(window).resize(function()

我恐怕我不懂語法 $(window)。。這是jquery特有的東西嗎?

最佳答案

讓我們分解 $(window).resize(function(){});

  • $ (an alias for jQuery) is simply the name of a JavaScript function. In this case, it's the jQuery object constructor function.

  • (window) - since we're calling a function, parameters are enclosed in parentheses. The jQuery function takes a number of parameters (selector strings, DOM element[s], other jQuery objects, and HTML strings). Here, we're passing the DOM window object, since we know it fires the onresize event that we want to bind to.

  • . - the jQuery() function returns a jQuery object—which has many methods and properties—and we use a period to access those methods.

  • resize() is a method of the jQuery object. Depending on the arguments you pass to it, it either triggers the resize event (when you pass no arguments) or binds a new event handler to the event (when you pass a function reference, like we are here). Bound event handler(s) are called each time the event is triggered by code or by the browser.

  • function() { } is the syntax for an anonymous function. The code you would write inside the { } gets executed each time the function is called. In this case, the function is called when the resize event is triggered.

轉載註明原文: 關於javascript事件處理程序語法的問題