Home > CMS Tutorial > WordPress > body text

14 jQuery tips, reminders, and best practices to improve your skills

王林
Release: 2023-08-30 13:05:09
Original
1254 people have browsed it

提高您技能的 14 个 jQuery 技巧、提醒和最佳实践

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');
Copy after login

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();
Copy after login

The reason we "cache" the position of a
someDiv

element 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();
Copy after login

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. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:javascript;toolbal:false;"> // Fine in modern browsers, though Sizzle does begin &quot;running&quot; $('#someDiv p.someClass').hide(); // Better for all browsers, and Sizzle never inits. $('#someDiv').find('p.someClass').hide(); </pre><div class="contentsignin">Copy after login</div></div>

The latest modern browsers support
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.

// Rough idea of how it works
 ['#someDiv, 'p'];
Copy after login

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,
id

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. When using Sizzle, optimize the rightmost part of the selector whenever possible.
  • Context?

You can also add context to the selector, for example:

$('.someElements', '#someContainer').hide();
Copy after login

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. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:javascript;toolbal:false;"> $('#someContainer') .find('.someElements') .hide(); </pre><div class="contentsignin">Copy after login</div></div> prove

// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
   return jQuery( context ).find( selector );
}
Copy after login


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') );
});
Copy after login

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. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:javascript;toolbal:false;"> $('#someAnchor').click(function() { alert( this.id ); }); </pre><div class="contentsignin">Copy after login</div></div>

Please note that there are three properties that should always be accessed through jQuery: "src", "href" and "style". These attributes require
getAttribute

in 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 );
Copy after login

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();
Copy after login

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

. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:javascript;toolbal: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><div class="contentsignin">Copy after login</div></div>


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
});
Copy after login

However, you've most likely encountered different, more confusing wrapper functions.

$(function() {
	// let's get up in heeya
});
Copy after login

尽管后者的可读性稍差,但上面的两个片段是相同的。不相信我?只需检查 jQuery 源代码即可。

// HANDLE: $(function)
// Shortcut for document ready
if ( jQuery.isFunction( selector ) ) {
	return rootjQuery.ready( selector );
}
Copy after login

rootjQuery 只是对根 jQuery(document) 的引用。当您将选择器传递给 jQuery 函数时,它将确定您传递的选择器类型:字符串、标记、id、函数等。如果传递了函数,jQuery 将调用其 ready() 方法,并将您的匿名函数作为选择器传递。


<跨度>5。 保证代码安全

如果开发用于分发的代码,补偿任何可能的名称冲突始终很重要。如果在您的脚本之后导入的某些脚本也具有 $ 函数,会发生什么情况?坏东西!

答案是要么调用 jQuery 的 noConflict(),要么将代码存储在自调用匿名函数中,然后将 jQuery 传递给它。

方法一:无冲突

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';
Copy after login

请小心使用此方法,并在分发代码时尽量不要使用它。这真的会让脚本的用户感到困惑! :)

方法二:传递jQuery

(function($) {
	// Within this function, $ will always refer to jQuery
})(jQuery);
Copy after login

底部的最后一个括号自动调用该函数 - function(){}()。然而,当我们调用该函数时,我们还传递了 jQuery,然后用 $ 表示。

方法3:通过Ready方法传递$

jQuery(document).ready(function($) {
 // $ refers to jQuery
});

// $ is either undefined, or refers to some other library's function.
Copy after login

<跨度>6。 要聪明

请记住 - jQuery 只是 JavaScript。不要假设它有能力弥补你的错误编码。 :)

这意味着,正如我们必须优化 JavaScript for 语句等内容一样,jQuery 的 each 方法也是如此。我们为什么不呢?它只是一个辅助方法,然后在幕后创建 for 语句。

// 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;
	}
Copy after login

太糟糕了

someDivs.each(function() {
	$('#anotherDiv')[0].innerHTML += $(this).text();
});
Copy after login
  1. 每次迭代搜索 anotherDiv
  2. 获取innerHTML 属性两次
  3. 创建一个新的 jQuery 对象,全部用于访问元素的文本。

更好

var someDivs = $('#container').find('.someDivs'),
      contents = [];

someDivs.each(function() {
	contents.push( this.innerHTML );
});
$('#anotherDiv').html( contents.join('') );
Copy after login

这样,在 each (for) 方法中,我们执行的唯一任务就是向数组添加一个新键...而不是查询 DOM,两次获取元素的 innerHTML 属性,等等

这篇技巧总体上更多地基于 JavaScript,而不是特定于 jQuery。 重点是要记住 jQuery 并不能弥补糟糕的编码。

文档片段

当我们这样做时,针对此类情况的另一种选择是使用文档片段。

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 );
Copy after login

这里的关键是,有多种方法可以完成这样的简单任务,并且每种方法在浏览器之间都有自己的性能优势。您越坚持使用 jQuery 并学习 JavaScript,您可能还会发现您更频繁地引用 JavaScript 的本机属性和方法。如果是这样,那就太棒了!

jQuery 提供了令人惊叹的抽象级别,您应该利用它,但这并不意味着您被迫使用它的方法。例如,在上面的片段示例中,我们使用 jQuery 的 each 方法。如果您更喜欢使用 forwhile 语句,那也没关系!

尽管如此,请记住 jQuery 团队已经对该库进行了大量优化。关于 jQuery 的 each() 与本机 for 语句的争论是愚蠢而琐碎的。如果您在项目中使用 jQuery,请使用它们的帮助器方法来节省时间。这就是他们存在的目的! :)


7。 AJAX 方法

如果您现在才开始深入研究 jQuery,它为我们提供的各种 AJAX 方法可能会让人感到有点畏惧;尽管他们不需要。事实上,它们中的大多数只是简单的辅助方法,直接路由到 $.ajax

  • 获取
  • getJSON
  • 帖子
  • ajax

作为示例,让我们回顾一下 getJSON,它允许我们获取 JSON。

$.getJSON('path/to/json', function(results) {
	// callback
	// results contains the returned data object
});
Copy after login
Copy after login

在幕后,该方法首先调用 $.get

getJSON: function( url, data, callback ) {
	return jQuery.get(url, data, callback, "json");
}
Copy after login

$.get 然后编译传递的数据,并再次调用“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
	});
}
Copy after login

最后,$.ajax 执行了大量工作,使我们能够在所有浏览器上成功发出异步请求!

这意味着您也可以直接使用 $.ajax 方法来处理您的所有 AJAX 请求。其他方法只是辅助方法,无论如何最终都会执行此操作。所以,如果你愿意的话,就可以去掉中间人。无论如何,这都不是一个重要的问题。

只是花花公子

$.getJSON('path/to/json', function(results) {
	// callback
	// results contains the returned data object
});
Copy after login
Copy after login

微观上更高效

$.ajax({
	type: 'GET',
	url : 'path/to/json',
	data : yourData,
	dataType : 'json',
	success : function( results ) {
		console.log('success');
	})
});
Copy after login

<跨度>8。 访问本机属性和方法

现在您已经学习了一些 JavaScript,并且已经了解,例如,在锚标记上,您可以直接访问属性值:

var anchor = document.getElementById('someAnchor');
 //anchor.id
// anchor.href
// anchor.title
// .etc
Copy after login

唯一的问题是,当您使用 jQuery 引用 DOM 元素时,这似乎不起作用,对吗?当然不是。

不起作用

	// Fails
	var id = $('#someAnchor').id;
Copy after login

因此,如果您需要访问 href 属性(或任何其他本机属性或方法),您有多种选择。

// 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;
Copy after login

get 方法特别有用,因为它可以将 jQuery 集合转换为数组。


<跨度>9。 使用 PHP 检测 AJAX 请求

当然,对于我们的绝大多数项目,我们不能仅仅依赖 JavaScript 来完成诸如验证或 AJAX 请求之类的事情。当 JavaScript 关闭时会发生什么?正是出于这个原因,一种常见的技术是检测 AJAX 请求是否是使用您选择的服务器端语言发出的。

jQuery 通过在 $.ajax 方法中设置标头,使这变得异常简单。

// 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");
}
Copy after login

设置此标头后,我们现在可以使用 PHP(或任何其他语言)检查此标头,并进行相应操作。为此,我们检查 $_SERVER['HTTP_X_REQUESTED_WITH'] 的值。

包装器

function isXhr() {
  return $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
Copy after login

<跨度>10。 jQuery 和 $

有没有想过为什么/如何可以互换使用 jQuery$ ?要找到答案,请查看 jQuery 源代码,然后滚动到最底部。在那里,您会看到:

window.jQuery = window.$ = jQuery;
Copy after login

当然,整个 jQuery 脚本都包含在一个自执行函数中,这允许脚本尽可能地限制全局变量的数量。但这也意味着 jQuery 对象在包装匿名函数之外不可用。

为了解决这个问题,jQuery 被暴露给全局 window 对象,并且在此过程中,还会创建一个别名 - $ -。


<跨度>11。 有条件地加载 jQuery

HTML5 Boilerplate 提供了一个漂亮的单行代码,如果由于某种奇怪的原因您选择的 CDN 出现故障,它将加载 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>
Copy after login

“表述”上面的代码:如果 window.jQuery 未定义,则从 CDN 下载脚本时一定出现问题。在这种情况下,请继续到 && 运算符的右侧,并插入链接到本地​​版本 jQuery 的脚本。


<跨度>12。 jQuery 过滤器

高级会员:下载此视频(必须登录)

订阅我们的 YouTube 页面以观看所有视频教程!

<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>
Copy after login

注意:jQuery.expr[':'] 只是 jQuery.expr.filters 的别名。


<跨度>13。 单一悬停功能

从 jQuery 1.4 开始,我们现在只能将单个函数传递给 hover 方法。以前,inout 方法都是必需的。

之前

$('#someElement').hover(function() {
  // mouseover
}, function() {
 // mouseout
});
Copy after login

现在

$('#someElement').hover(function() {
  // the toggle() method can be used here, if applicable
});
Copy after login

请注意,这不是旧协议与新协议的比较。很多时候,您仍然需要将两个函数传递给 hover,这是完全可以接受的。但是,如果您只需要切换某些元素(或类似的元素),则传递单个匿名函数将节省一些字符左右!


14。 传递属性对象

从 jQuery 1.4 开始,我们现在可以传递一个对象作为 jQuery 函数的第二个参数。当我们需要向 DOM 中插入新元素时,这非常有用。例如:

之前

$('<a />')
  .attr({
    id : 'someId',
    className : 'someClass',
    href : 'somePath.html'
  });
Copy after login

之后

$('</a>', {
    id : 'someId',
    className : 'someClass',
    href : 'somePath.html'
});
Copy after login

这不仅可以节省一些字符,而且还可以使代码更加简洁。除了元素属性之外,我们甚至可以传递 jQuery 特定的属性和事件,例如 clicktext


感谢您的阅读!

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!