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 forjQuery
) 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. ThejQuery
function takes a number of parameters (selector strings, DOM element[s], other jQuery objects, and HTML strings). Here, we're passing the DOMwindow
object, since we know it fires theonresize
event that we want to bind to..
- thejQuery()
function returns ajQuery
object—which has many methods and properties—and we use a period to access those methods.resize()
is a method of thejQuery
object. Depending on the arguments you pass to it, it either triggers theresize
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 theresize
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
精彩评论