开发者

Question about javascript event handler syntax

My question appears to have been deleted yesterday before it could be answered, so I'm starting a new thread on the subject.

I've been trying to find cross-browser resize javascript, and ran across this syntax in one answer posted here:

$(window).resize(function()

I'm 开发者_运维百科afraid I don't understand the syntax $(window).. Is that something specific to jquery?


You added your question as an answer to an old question. This is the right way to do it!

$(window) is jQuery syntax for creating a jQuery object that contains the window object. Certain events are triggered on this, for instance resize, load, etc.

This syntax adds a resize handler to the window.


Let's break down $(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.


The "$" character in JavaScript can be used freely in variable and function names. Thus, jQuery uses the identifier "$" as an alias for the "jQuery" function.

You can do this yourself:

var my$variable = "hello world";
alert(my$variable);

Or

function my$function() { ... }


Yes. See http://api.jquery.com/jQuery/


Yes, this is specific to jQuery. Which is cross browser and free to download. I would suggest using jQuery for this since it takes care of all the cross browser difficulties for you. The $(window) is shorthand for jQuery(window) which selects the browser window and any options, events, and anything else that is associated with it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜