标签:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write(‘<script src="js/jquery-2.1.1.min.js" type="text/javascript"><\/script>‘)</script>
Click here for a list of popular jQuery CDNs.http:
or https:
out) as shown above.$
sign as well, try not to use $
for calling jQuery functions and instead use jQuery
simply. You can return control of $
back to the other library with a call to $.noConflict()
.$
.var $myDiv = $("#myDiv");
$myDiv.click(function(){...});
document.getElementById()
.var $products = $("div.products"); // SLOW
var $products = $(".products"); // FAST
.find()
approach is faster because the first selection is handled without going through the Sizzle selector engine. More Info
// BAD, a nested query for Sizzle selector engine
var $productIds = $("#products div.id");
// GOOD, #products is already selected by document.getElementById() so only div.id needs to go through Sizzle selector engine
var $productIds = $("#products").find("div.id");
// Unoptimized
$("div.data .gonzalez");
// Optimized
$(".data td.gonzalez");
$(".data table.attendees td.gonzalez");
// Better: Drop the middle if possible.
$(".data td.gonzalez");
// SLOWER because it has to traverse the whole DOM for .class
$(‘.class‘);
// FASTER because now it only looks under class-container.
$(‘.class‘, ‘#class-container‘);
$(‘div.container > *‘); // BAD
$(‘div.container‘).children(); // BETTER
$(‘div.someclass :radio‘); // BAD
$(‘div.someclass input:radio‘); // GOOD
document.getElementById()
so don‘t mix them with other selectors.
$(‘#outer #inner‘); // BAD
$(‘div#inner‘); // BAD
$(‘.outer-container #inner‘); // BAD
$(‘#inner‘); // GOOD, only calls document.getElementById()
var $myList = $("#list-container > ul").detach();
//...a lot of complicated things on $myList
$myList.appendTo("#list-container");
array.join()
over .append()
. More Info // BAD
var $myList = $("#list");
for(var i = 0; i < 10000; i++){
$myList.append("<li>"+i+"</li>");
}
// GOOD
var $myList = $("#list");
var list = "";
for(var i = 0; i < 10000; i++){
list += "<li>"+i+"</li>";
}
$myList.html(list);
// EVEN FASTER
var array = [];
for(var i = 0; i < 10000; i++){
array[i] = "<li>"+i+"</li>";
}
$myList.html(array.join(‘‘));
// BAD: This runs three functions before it realizes there‘s nothing in the selection
$("#nosuchthing").slideUp();
// GOOD
var $mySelection = $("#nosuchthing");
if ($mySelection.length) {
$mySelection.slideUp();
}
$("#myLink").on("click", function(){...}); // BAD
// GOOD
function myLinkClickHandler(){...}
$("#myLink").on("click", myLinkClickHandler);
$(function(){ ... }); // BAD: You can never reuse or write a test for this function.
// GOOD
$(initPage); // or $(document).ready(initPage);
function initPage(){
// Page load event where you can initialize values and call other initializers.
}
<script src="my-document-ready.js"></script>
<script>
// Any global variable set-up that might be needed.
$(document).ready(initPage); // or $(initPage);
</script>
<a id="myLink" href="#" onclick="myEventHandler();">my link</a> <!-- BAD -->
$("#myLink").on("click", myEventHandler); // GOOD
$("#myLink").on("click.mySpecialClick", myEventHandler); // GOOD
// Later on, it‘s easier to unbind just your click event
$("#myLink").unbind("click.mySpecialClick");
$("#list a").on("click", myClickHandler); // BAD, you are attaching an event to all the links under the list.
$("#list").on("click", "a", myClickHandler); // GOOD, only one event handler is attached to the parent.
// Less readable...
$.ajax({
url: "something.php?param1=test1¶m2=test2",
....
});
// More readable...
$.ajax({
url: "something.php",
data: { param1: test1, param2: test2 }
});
$("#parent-container").on("click", "a", delegatedClickHandlerForAjax);
$.ajax({ ... }).then(successHandler, failureHandler);
// OR
var jqxhr = $.ajax({ ... });
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
var jqxhr = $.ajax({
url: url,
type: "GET", // default is GET but you can use other verbs based on your needs.
cache: true, // default is true, but false for dataType ‘script‘ and ‘jsonp‘, so set it on need basis.
data: {}, // add your request parameters in the data object.
dataType: "json", // specify the dataType for future reference
jsonp: "callback", // only specify this to match the name of callback parameter your API is expecting for JSONP requests.
statusCode: { // if you want to handle specific error codes, use the status code mapping settings.
404: handler404,
500: handler500
}
});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
$("#myDiv").addClass("error").show();
$("#myLink")
.addClass("bold")
.on("click", myClickHandler)
.on("mouseover", myMouseOverHandler)
.show();
$myLink.attr("href", "#").attr("title", "my link").attr("rel", "external"); // BAD, 3 calls to attr()
// GOOD, only 1 call to attr()
$myLink.attr({
href: "#",
title: "my link",
rel: "external"
});
$("#mydiv").css({‘color‘:red, ‘font-weight‘:‘bold‘}); // BAD
.error { color: red; font-weight: bold; } /* GOOD */
$("#mydiv").addClass("error"); // GOOD
$("#myId"); // is still little slower than...
document.getElementById("myId");
Coding Standards & Best Practices
标签:
原文地址:http://www.cnblogs.com/jsmiao/p/4772784.html