10
09/2014
jquery best practices
jquery 好处
- The DOM sucks without it
- Ajax and JSONP suck without it
- jQuery Utility functions are rad
- jQuery Deferreds/Promises are really rad
via jquery best practices 笔记如下:
jsbin
// IIFE - Immediately Invoked Function Expression (function(yourcode) { // The global jQuery object is passed as a parameter yourcode(window.jQuery, window, document); }(function($, window, document) { // The $ is now locally scoped // Listen for the jQuery ready event on the document $(function() { // The DOM is ready! }); // The rest of the code goes here! } }));
cache selectors in vars(少 DOM)
// Stores the live DOM element inside of a variable var elem = $("#elem"); // Set's an element's title attribute using it's current text elem.attr("title", elem.text()); // Set's an element's text color to red elem.css("color", "red"); // Makes the element fade out elem.fadeOut();
Append once(少 DOM)
// Dynamically building an unordered list from an array var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"], list = $("ul.people"), dynamicItems = ""; $.each(localArr, function(index, value) { dynamicItems += "
event delegation
var list = $("#longlist"); list.on("mouseenter", "li", function(){ $(this).text("Click me!"); }); list.on("click", "li", function() { $(this).text("Why did you click me?!"); });
Ajax
function getName(personid) { var dynamicData = {}; dynamicData["id"] = personID; return $.ajax({ url: "getName.php", type: "get", data: dynamicData }); } getName("2342342").done(function(data) { // Updates the UI based the ajax result $(".person-name").text(data.name); });
其它话题
- jQuery and CSS
- jQuery Custom Events - Pub/Sub
- jQuery and Object Literals
- jQuery Utility Functions
- jQuery Event Namespaces
- The future of jQuery
- jQuery Event Namespaces
- Authoring jQuery Plugins
- Return False vs Event.preventDefault()
- Animation with Promises