So, to start things off, why use jQuery? Well, basically, jQuery is a javascript that works well. It simplifies a lot of the things in javascript, and makes things more intuitive. Just as a quick example, take the simple task of toggling visibility of a div on your page.
Take a simple page:
Toggle DivThis is some toggling text
Here is the code for toggling visibility in javascript:
Here is the code for toggling visibility in jQuery:
That was an 8 line reduction in code, not to mention a heck of a lot easier to understand.
The key to understanding most of jQuery is to look at it's selector technology. That is all the stuff inside the $() in the code snippet above. jQuery uses the $ as it's primary object - in fact, there are several things you can do just with $.whatever. With parens after the $, it means that it is searching for stuff.
The selector syntax is very similar, if not identical, to the CSS selector syntax. For example, if you do $("div"), that will return all of the divs on the page. Better yet, jQuery will take any operation you perform, and apply it to everything that is returned by the selector, so that $("div").toggle() would toggle the visibility of every single div on the page.
Just to cover some of the basics of the selector syntax, here is a quick and dirty list of some of the commonly used things:
- "#" - used to reference a particular ID, such as $("#mydivid")
- "." - used to reference a class name, such as $(".myclassname")
- "," - used to concatenate selectors, such as $("#firstdiv, #seconddiv") to select both the div with the ID "firstdiv" and the div with the ID "seconddiv"
- " " - used for hierarchy of selectors, such as $("#mydivid a") to select all links that are children of the div with the id "mydivid"
- val()/val("blah") - used to get or set the value of a form field
- css("cssattr")/css("cssattr","attrval") - used to get or set any css attribute on the object
- attr("attrname")/attr("attrname","attrval") - used to get or set any html attribute on the object
- insertBefore(object)/insertAfter(object) - used to add new html objects to the page
- parent()/children() - used to get the parent object or the children objects of the object
No comments:
Post a Comment