If there's one bad thing about jQuery, it's that the entry level is so incredibly low that it tends to attract people who don't know a thing about JavaScript. Now, on one hand, this is awesome. However, on the other hand, it can also lead to some, frankly, disgustingly bad code (some of which I wrote myself!). But that’s okay; coding so horribly bad that it would make your grandma gasp is a rite of passage. The key is to get over the mountain, and that's what we're going to talk about in today's tutorial.
1.
Method returns jQuery object It is important to remember that most methods return jQuery objects. This is very useful and allows for linking functionality that we use frequently.
$someDiv .attr('class', 'someClass') .hide() .html('new stuff');
Knowing that jQuery objects are always returned, we can sometimes use this to remove redundant code. For example, consider the following code:
var someDiv = $('#someDiv'); someDiv.hide();
The reason we "cache" the position of a
someDivelement is to limit the number of times we have to traverse that element's DOM to just once.
The above code is perfectly fine; however, you can easily merge the two lines into one while getting the same result.
var someDiv = $('#someDiv').hide();
This way, we still hide the
someDiv element, but as we know, the method also returns a jQuery object - which is then referenced through the someDiv
variable.
2.
Find selector<跨度> As long as your selectors aren't ridiculously bad, jQuery will optimize them as much as possible, and you usually don't need to worry too much about them. However, having said that, there are some improvements you can make that will slightly improve the performance of your script.
One such solution is to use the
find() method where possible. The key is not to force jQuery to use its Sizzle engine if you don't have to. Of course, sometimes this isn't possible - and that's okay; however, if you don't need the extra overhead, don't look for it.
<pre class='brush:php;toolbar:false;'>
// Fine in modern browsers, though Sizzle does begin "running"
$('#someDiv p.someClass').hide();
// Better for all browsers, and Sizzle never inits.
$('#someDiv').find('p.someClass').hide();
</pre>
QuerySelectorAll, which allows you to pass CSS-like selectors without the need for jQuery. jQuery itself also checks this function.
However, older browsers (i.e. IE6/IE7) do not provide support, which is understandable. This means that these more complex selectors trigger jQuery's full Sizzle engine, which, while great, does come with more overhead.
Sizzle is a bunch of wonderful code that I may never understand. However, in one sentence, it first turns your selector into an "array" consisting of each component of the selector.
id
// Rough idea of how it works ['#someDiv, 'p'];Then, from right to left, start deciphering each item using regular expressions. This also means that the right-most part of the selector should be as specific as possible - for example,
or the tag name.
Bottom line, if possible:
Keep selectors simple
- Use the find()
- method. This way, we can continue to use the browser's native functionality instead of using Sizzle.
- Context?
You can also add context to the selector, for example:
$('.someElements', '#someContainer').hide();
This code instructs jQuery to wrap a collection of all elements in jQuery using the
someElements class (which is a child of someContainer
). Using context is a useful way to limit DOM traversal, but behind the scenes, jQuery uses the find
method instead.
<pre class='brush:php;toolbar:false;'>
$('#someContainer')
.find('.someElements')
.hide();
</pre>
prove
// HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); }
3.
Don’t abuse<跨度>$(this)
Without understanding the various DOM properties and capabilities, it's easy to misuse jQuery objects unnecessarily. For example:
$('#someAnchor').click(function() { // Bleh alert( $(this).attr('id') ); });
If our only need for the jQuery object is to access the
id property of the anchor tag, then this is wasteful. It's better to stick to "raw" JavaScript.
<pre class='brush:php;toolbar:false;'>
$('#someAnchor').click(function() {
alert( this.id );
});
</pre>
getAttributein older versions of IE.
prove
// jQuery Source var rspecialurl = /href|src|style/; // ... var special = rspecialurl.test( name ); // ... var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name );
Multiple jQuery objects
Even worse is the process of repeatedly querying the DOM and creating multiple jQuery objects.
$('#elem').hide(); $('#elem').html('bla'); $('#elem').otherStuff();
Hopefully you've realized how inefficient this code is. If not, that's okay; we're all learning. The answer is to either implement linking or "cache" the location of
#elem.
<pre class='brush:php;toolbar:false;'>
// This works better
$('#elem')
.hide()
.html('bla')
.otherStuff();
// Or this, if you prefer for some reason.
var elem = $('#elem');
elem.hide();
elem.html('bla');
elem.otherStuff();
</pre>
4.
Abbreviation of jQueryReadyMethod
It's very simple to use jQuery to listen for when a document is ready for action.
$(document).ready(function() { // let's get up in heeya });
However, you've most likely encountered different, more confusing wrapper functions.
$(function() { // let's get up in heeya });
盡管后者的可讀性稍差,但上面的兩個(gè)片段是相同的。不相信我?只需檢查 jQuery 源代碼即可。
// HANDLE: $(function) // Shortcut for document ready if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }
rootjQuery
只是對(duì)根 jQuery(document)
的引用。當(dāng)您將選擇器傳遞給 jQuery 函數(shù)時(shí),它將確定您傳遞的選擇器類型:字符串、標(biāo)記、id、函數(shù)等。如果傳遞了函數(shù),jQuery 將調(diào)用其 ready()
方法,并將您的匿名函數(shù)作為選擇器傳遞。
<跨度>5。 保證代碼安全
如果開(kāi)發(fā)用于分發(fā)的代碼,補(bǔ)償任何可能的名稱沖突始終很重要。如果在您的腳本之后導(dǎo)入的某些腳本也具有 $
函數(shù),會(huì)發(fā)生什么情況?壞東西!
答案是要么調(diào)用 jQuery 的 noConflict()
,要么將代碼存儲(chǔ)在自調(diào)用匿名函數(shù)中,然后將 jQuery 傳遞給它。
方法一:無(wú)沖突
var j = jQuery.noConflict(); // Now, instead of $, we use j. j('#someDiv').hide(); // The line below will reference some other library's $ function. $('someDiv').style.display = 'none';
請(qǐng)小心使用此方法,并在分發(fā)代碼時(shí)盡量不要使用它。這真的會(huì)讓腳本的用戶感到困惑! :)
方法二:傳遞jQuery
(function($) { // Within this function, $ will always refer to jQuery })(jQuery);
底部的最后一個(gè)括號(hào)自動(dòng)調(diào)用該函數(shù) - function(){}()
。然而,當(dāng)我們調(diào)用該函數(shù)時(shí),我們還傳遞了 jQuery,然后用 $
表示。
方法3:通過(guò)Ready
方法傳遞$
jQuery(document).ready(function($) { // $ refers to jQuery }); // $ is either undefined, or refers to some other library's function.
<跨度>6。 要聰明
請(qǐng)記住 - jQuery 只是 JavaScript。不要假設(shè)它有能力彌補(bǔ)你的錯(cuò)誤編碼。 :)
這意味著,正如我們必須優(yōu)化 JavaScript for
語(yǔ)句等內(nèi)容一樣,jQuery 的 each
方法也是如此。我們?yōu)槭裁床荒??它只是一個(gè)輔助方法,然后在幕后創(chuàng)建 for
語(yǔ)句。
// jQuery's each method source each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }
太糟糕了
someDivs.each(function() { $('#anotherDiv')[0].innerHTML += $(this).text(); });
- 每次迭代搜索
anotherDiv
- 獲取innerHTML 屬性兩次
- 創(chuàng)建一個(gè)新的 jQuery 對(duì)象,全部用于訪問(wèn)元素的文本。
更好
var someDivs = $('#container').find('.someDivs'), contents = []; someDivs.each(function() { contents.push( this.innerHTML ); }); $('#anotherDiv').html( contents.join('') );
這樣,在 each
(for) 方法中,我們執(zhí)行的唯一任務(wù)就是向數(shù)組添加一個(gè)新鍵...而不是查詢 DOM,兩次獲取元素的 innerHTML
屬性,等等
這篇技巧總體上更多地基于 JavaScript,而不是特定于 jQuery。 重點(diǎn)是要記住 jQuery 并不能彌補(bǔ)糟糕的編碼。
文檔片段
當(dāng)我們這樣做時(shí),針對(duì)此類情況的另一種選擇是使用文檔片段。
var someUls = $('#container').find('.someUls'), frag = document.createDocumentFragment(), li; someUls.each(function() { li = document.createElement('li'); li.appendChild( document.createTextNode(this.innerHTML) ); frag.appendChild(li); }); $('#anotherUl')[0].appendChild( frag );
這里的關(guān)鍵是,有多種方法可以完成這樣的簡(jiǎn)單任務(wù),并且每種方法在瀏覽器之間都有自己的性能優(yōu)勢(shì)。您越堅(jiān)持使用 jQuery 并學(xué)習(xí) JavaScript,您可能還會(huì)發(fā)現(xiàn)您更頻繁地引用 JavaScript 的本機(jī)屬性和方法。如果是這樣,那就太棒了!
jQuery 提供了令人驚嘆的抽象級(jí)別,您應(yīng)該利用它,但這并不意味著您被迫使用它的方法。例如,在上面的片段示例中,我們使用 jQuery 的 each
方法。如果您更喜歡使用 for
或 while
語(yǔ)句,那也沒(méi)關(guān)系!
盡管如此,請(qǐng)記住 jQuery 團(tuán)隊(duì)已經(jīng)對(duì)該庫(kù)進(jìn)行了大量?jī)?yōu)化。關(guān)于 jQuery 的
each()
與本機(jī)for
語(yǔ)句的爭(zhēng)論是愚蠢而瑣碎的。如果您在項(xiàng)目中使用 jQuery,請(qǐng)使用它們的幫助器方法來(lái)節(jié)省時(shí)間。這就是他們存在的目的! :)
7。 AJAX 方法
如果您現(xiàn)在才開(kāi)始深入研究 jQuery,它為我們提供的各種 AJAX 方法可能會(huì)讓人感到有點(diǎn)畏懼;盡管他們不需要。事實(shí)上,它們中的大多數(shù)只是簡(jiǎn)單的輔助方法,直接路由到 $.ajax
。
- 獲取
- getJSON
- 帖子
- ajax
作為示例,讓我們回顧一下 getJSON
,它允許我們獲取 JSON。
$.getJSON('path/to/json', function(results) { // callback // results contains the returned data object });
在幕后,該方法首先調(diào)用 $.get
。
getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }
$.get
然后編譯傳遞的數(shù)據(jù),并再次調(diào)用“master”(某種意義上的)$.ajax
方法。
get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }
最后,$.ajax
執(zhí)行了大量工作,使我們能夠在所有瀏覽器上成功發(fā)出異步請(qǐng)求!
這意味著您也可以直接使用
$.ajax
方法來(lái)處理您的所有 AJAX 請(qǐng)求。其他方法只是輔助方法,無(wú)論如何最終都會(huì)執(zhí)行此操作。所以,如果你愿意的話,就可以去掉中間人。無(wú)論如何,這都不是一個(gè)重要的問(wèn)題。
只是花花公子
$.getJSON('path/to/json', function(results) { // callback // results contains the returned data object });
微觀上更高效
$.ajax({ type: 'GET', url : 'path/to/json', data : yourData, dataType : 'json', success : function( results ) { console.log('success'); }) });
<跨度>8。 訪問(wèn)本機(jī)屬性和方法
現(xiàn)在您已經(jīng)學(xué)習(xí)了一些 JavaScript,并且已經(jīng)了解,例如,在錨標(biāo)記上,您可以直接訪問(wèn)屬性值:
var anchor = document.getElementById('someAnchor'); //anchor.id // anchor.href // anchor.title // .etc
唯一的問(wèn)題是,當(dāng)您使用 jQuery 引用 DOM 元素時(shí),這似乎不起作用,對(duì)嗎?當(dāng)然不是。
不起作用
// Fails var id = $('#someAnchor').id;
因此,如果您需要訪問(wèn) href
屬性(或任何其他本機(jī)屬性或方法),您有多種選擇。
// OPTION 1 - Use jQuery var id = $('#someAnchor').attr('id'); // OPTION 2 - Access the DOM element var id = $('#someAnchor')[0].id; // OPTION 3 - Use jQuery's get method var id = $('#someAnchor').get(0).id; // OPTION 3b - Don't pass an index to get anchorsArray = $('.someAnchors').get(); var thirdId = anchorsArray[2].id;
get
方法特別有用,因?yàn)樗梢詫?jQuery 集合轉(zhuǎn)換為數(shù)組。
<跨度>9。 使用 PHP 檢測(cè) AJAX 請(qǐng)求
當(dāng)然,對(duì)于我們的絕大多數(shù)項(xiàng)目,我們不能僅僅依賴 JavaScript 來(lái)完成諸如驗(yàn)證或 AJAX 請(qǐng)求之類的事情。當(dāng) JavaScript 關(guān)閉時(shí)會(huì)發(fā)生什么?正是出于這個(gè)原因,一種常見(jiàn)的技術(shù)是檢測(cè) AJAX 請(qǐng)求是否是使用您選擇的服務(wù)器端語(yǔ)言發(fā)出的。
jQuery 通過(guò)在 $.ajax
方法中設(shè)置標(biāo)頭,使這變得異常簡(jiǎn)單。
// Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); }
設(shè)置此標(biāo)頭后,我們現(xiàn)在可以使用 PHP(或任何其他語(yǔ)言)檢查此標(biāo)頭,并進(jìn)行相應(yīng)操作。為此,我們檢查 $_SERVER['HTTP_X_REQUESTED_WITH']
的值。
包裝器
function isXhr() { return $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; }
<跨度>10。 jQuery 和 $
有沒(méi)有想過(guò)為什么/如何可以互換使用 jQuery
和 $
?要找到答案,請(qǐng)查看 jQuery 源代碼,然后滾動(dòng)到最底部。在那里,您會(huì)看到:
window.jQuery = window.$ = jQuery;
當(dāng)然,整個(gè) jQuery 腳本都包含在一個(gè)自執(zhí)行函數(shù)中,這允許腳本盡可能地限制全局變量的數(shù)量。但這也意味著 jQuery 對(duì)象在包裝匿名函數(shù)之外不可用。
為了解決這個(gè)問(wèn)題,jQuery 被暴露給全局 window
對(duì)象,并且在此過(guò)程中,還會(huì)創(chuàng)建一個(gè)別名 - $
-。
<跨度>11。 有條件地加載 jQuery
HTML5 Boilerplate 提供了一個(gè)漂亮的單行代碼,如果由于某種奇怪的原因您選擇的 CDN 出現(xiàn)故障,它將加載 jQuery 的本地副本。
<!-- Grab Google CDN jQuery. fall back to local if necessary --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>
“表述”上面的代碼:如果 window.jQuery 未定義,則從 CDN 下載腳本時(shí)一定出現(xiàn)問(wèn)題。在這種情況下,請(qǐng)繼續(xù)到 &&
運(yùn)算符的右側(cè),并插入鏈接到本地??版本 jQuery 的腳本。
<跨度>12。 jQuery 過(guò)濾器
高級(jí)會(huì)員:下載此視頻(必須登錄)
訂閱我們的 YouTube 頁(yè)面以觀看所有視頻教程!
<script> $('p:first').data('info', 'value'); // populates $'s data object to have something to work with $.extend( jQuery.expr[":"], { block: function(elem) { return $(elem).css("display") === "block"; }, hasData : function(elem) { return !$.isEmptyObject( $(elem).data() ); } } ); $("p:hasData").text("has data"); // grabs paras that have data attached $("p:block").text("are block level"); // grabs only paragraphs that have a display of "block" </script>
注意:
jQuery.expr[':']
只是jQuery.expr.filters
的別名。
<跨度>13。 單一懸停功能
從 jQuery 1.4 開(kāi)始,我們現(xiàn)在只能將單個(gè)函數(shù)傳遞給 hover
方法。以前,in 和 out 方法都是必需的。
之前
$('#someElement').hover(function() { // mouseover }, function() { // mouseout });
現(xiàn)在
$('#someElement').hover(function() { // the toggle() method can be used here, if applicable });
請(qǐng)注意,這不是舊協(xié)議與新協(xié)議的比較。很多時(shí)候,您仍然需要將兩個(gè)函數(shù)傳遞給 hover
,這是完全可以接受的。但是,如果您只需要切換某些元素(或類似的元素),則傳遞單個(gè)匿名函數(shù)將節(jié)省一些字符左右!
14。 傳遞屬性對(duì)象
從 jQuery 1.4 開(kāi)始,我們現(xiàn)在可以傳遞一個(gè)對(duì)象作為 jQuery 函數(shù)的第二個(gè)參數(shù)。當(dāng)我們需要向 DOM 中插入新元素時(shí),這非常有用。例如:
之前
$('<a />') .attr({ id : 'someId', className : 'someClass', href : 'somePath.html' });
之后
$('</a>', { id : 'someId', className : 'someClass', href : 'somePath.html' });
這不僅可以節(jié)省一些字符,而且還可以使代碼更加簡(jiǎn)潔。除了元素屬性之外,我們甚至可以傳遞 jQuery 特定的屬性和事件,例如 click
或 text
。
感謝您的閱讀!
The above is the detailed content of 14 jQuery tips, reminders, and best practices to improve your skills. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

1. Use performance analysis plug-in to quickly locate problems. For example, QueryMonitor can view the number of database queries and PHP errors, BlackboxProfiler generates function execution reports, and NewRelic provides server-level analysis; 2. Analyzing PHP execution performance requires checking time-consuming functions, debugging tools usage and memory allocation, such as Xdebug generates flame graphs to assist in optimization; 3. Monitor database query efficiency can be checked through slow query logs and index checks, QueryMonitor can list all SQL and sort by time; 4. Combining external tools such as GooglePageSpeedInsights, GTmetrix and WebPageTest to evaluate front-end plus
