语法

公鸡酸是“准备事件”的简称 鸡酮酸的断行性和链性 嵌套过滤器由Nathan Long 缓存一个集合并通过roosteronacid在同一行上执行命令 包含选择器roosteronacid 定义元素创建时的属性 访问jQuery函数就像访问roosteronacid数组一样 noConflict函数- Oli释放$变量 通过nickf隔离noConflict模式下的$变量 无冲突模式由鸡酮酸

数据存储

数据函数-通过TenebrousX将数据绑定到元素 HTML5数据属性支持,在类固醇!由roosteronacid Filip dupanovic设计的jQuery元数据插件

优化

用鸡酮酸优化复合选择剂的性能 lupefiasco的上下文参数 Nathan Long的保存和重用搜索 创建HTML元素并保持引用,检查元素是否存在,编写自己的选择器

杂项

Check the index of an element in a collection by redsquare Live event handlers by TM Replace anonymous functions with named functions by ken Microsoft AJAX framework and jQuery bridge by Slace jQuery tutorials by egyamado Remove elements from a collection and preserve chainability by roosteronacid Declare $this at the beginning of anonymous functions by Ben FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN by Colour Blend Judicious use of third-party jQuery scripts by harriyott The each function by Jan Zich Form Extensions plug-in by Chris S Asynchronous each function by OneNerd The jQuery template plug-in: implementing complex logic using render-functions by roosteronacid


我真的不喜欢$(document).ready(fn)快捷方式。当然,这减少了代码,但也降低了代码的可读性。当你看到$(document).ready(…)时,你知道你在看什么。$(…)被用于太多其他的方式,以至于没有立即的意义。

如果你有多个框架,你可以使用jQuery.noConflict();如你所说,但你也可以为它分配一个不同的变量,像这样:

var $j = jQuery.noConflict();

$j("#myDiv").hide();

如果你有几个框架可以归结为$x(…)风格的调用,这是非常有用的。


明智地使用第三方jQuery脚本,如表单字段验证或url解析。有必要了解一下它的内容,以便下次遇到JavaScript需求时了解情况。


我喜欢在匿名函数的开头声明一个$this变量,所以我知道我可以引用一个jquery this。

像这样:

$('a').each(function() {
    var $this = $(this);

    // Other code
});

不是真的jQuery,但我为jQuery和MS AJAX做了一个漂亮的小桥梁:

Sys.UI.Control.prototype.j = function Sys$UI$Control$j(){
  return $('#' + this.get_id());
}

如果你做了很多ASP,这真的很好。由于MS支持jQuery,现在有一个很好的桥接意味着它很容易做jQuery操作:

$get('#myControl').j().hide();

所以上面的例子不是很好,但是如果你正在编写ASP。NET AJAX服务器控件,使得在客户端控件实现中使用jQuery变得很容易。


jQuery的data()方法很有用,但并不广为人知。它允许在不修改DOM的情况下将数据绑定到DOM元素。


而不是使用不同的别名为jQuery对象(当使用noConflict),我总是写我的jQuery代码包装在一个闭包。这可以在文档中完成。现成的函数:

var $ = someOtherFunction(); // from a different library

jQuery(function($) {
    if ($ instanceOf jQuery) {
        alert("$ is the jQuery object!");
    }
});

或者你可以这样做:

(function($) {
    $('...').etc()    // whatever jQuery code you want
})(jQuery);

我觉得这个最方便携带。我一直在一个同时使用Prototype和jQuery的网站上工作,这些技术避免了所有的冲突。


创建一个HTML元素并保留一个引用

var newDiv = $("<div />");

newDiv.attr("id", "myNewDiv").appendTo("body");

/* Now whenever I want to append the new div I created, 
   I can just reference it from the "newDiv" variable */

检查元素是否存在

if ($("#someDiv").length)
{
    // It exists...
}

编写自己的选择器

$.extend($.expr[":"], {
    over100pixels: function (e)
    {
        return $(e).height() > 100;
    }
});

$(".box:over100pixels").click(function ()
{
    alert("The element you clicked is over 100 pixels height");
});

嵌套过滤器

可以嵌套过滤器(如nickf所示)。

.filter(":not(:has(.selected))")

将jQuery对象保存在变量中以供重用

将jQuery对象保存为变量可以让您重用它,而不必通过DOM重新查找它。

(正如@Louis所建议的,我现在使用$表示变量保存jQuery对象。)

// Bad: searching the DOM multiple times for the same elements
$('div.foo').each...
$('div.foo').each...

// Better: saving that search for re-use
var $foos = $('div.foo');
$foos.each...
$foos.each...

举一个更复杂的例子,假设您在商店中有一个食品列表,您希望只显示符合用户标准的食品。您有一个带有复选框的表单,每个复选框包含一个标准。复选框有像有机和低脂肪这样的名称,产品有相应的类别- .organic,等等。

var $allFoods, $matchingFoods;
$allFoods = $('div.food');

现在可以继续使用jQuery对象了。每次点击一个复选框(选中或取消选中),从食物的主列表开始,并根据选中的复选框进行筛选:

// Whenever a checkbox in the form is clicked (to check or uncheck)...
$someForm.find('input:checkbox').click(function(){

  // Start out assuming all foods should be showing
  // (in case a checkbox was just unchecked)
  var $matchingFoods = $allFoods;

  // Go through all the checked boxes and keep only the foods with
  // a matching class 
  this.closest('form').find("input:checked").each(function() {  
     $matchingFoods = $matchingFoods.filter("." + $(this).attr("name")); 
  });

  // Hide any foods that don't match the criteria
  $allFoods.not($matchingFoods).hide();
});

检查索引

jQuery有.index,但使用起来很痛苦,因为你需要元素列表,并传入你想要索引的元素:

var index = e.g $('#ul>li').index( liDomObject );

下面的方法就简单多了:

如果你想知道无序列表中集合(例如列表项)中元素的索引:

$("ul > li").click(function () {
    var index = $(this).prevAll().length;
});

在核心jQuery函数中,除了指定选择器参数外,还指定上下文参数。指定context参数允许jQuery从DOM中更深的分支开始,而不是从DOM根开始。给定一个足够大的DOM,指定上下文参数应该转化为性能提升。

示例:查找文档中第一个表单中radio类型的所有输入。

$("input:radio", document.forms[0]);

参考:http://docs.jquery.com/Core/jQuery # expressioncontext


哦,不要忘了jQuery元数据!data()函数很棒,但它必须通过jQuery调用来填充。

而不是打破W3C的自定义元素属性,如:

<input 
  name="email" 
  validation="required" 
  validate="email" 
  minLength="7" 
  maxLength="30"/> 

使用元数据:

<input 
  name="email" 
  class="validation {validate: email, minLength: 2, maxLength: 50}" />

<script>
    jQuery('*[class=validation]').each(function () {
        var metadata = $(this).metadata();
        // etc.
    });
</script>

缓存一个对象集合,并在一行中执行命令:

而不是:

var jQueryCollection = $("");

jQueryCollection.command().command();

我做的事:

var jQueryCollection = $("").command().command();

一个有点“真实”的用例可能是这样的:

var cache = $("#container div.usehovereffect").mouseover(function ()
{
    cache.removeClass("hover").filter(this).addClass("hover");
});

Replace anonymous functions with named functions. This really supercedes the jQuery context, but it comes into play more it seems like when using jQuery, due to its reliance on callback functions. The problems I have with inline anonymous functions, are that they are harder to debug (much easier to look at a callstack with distinctly-named functions, instead 6 levels of "anonymous"), and also the fact that multiple anonymous functions within the same jQuery-chain can become unwieldy to read and/or maintain. Additionally, anonymous functions are typically not re-used; on the other hand, declaring named functions encourages me to write code that is more likely to be re-used.

一个例子;而不是:

$('div').toggle(
    function(){
        // do something
    },
    function(){
        // do something else
    }
);

我喜欢:

function onState(){
    // do something
}

function offState(){
    // do something else
}

$('div').toggle( offState, onState );

实时事件处理程序

为任何匹配选择器的元素设置一个事件处理程序,即使它在初始页面加载后被添加到DOM:

$('button.someClass').live('click', someFunction);

这允许您通过ajax加载内容,或通过javascript添加内容,并自动为这些元素正确设置事件处理程序。

同样地,要停止实时事件处理:

$('button.someClass').die('click', someFunction);

与常规事件相比,这些实时事件处理程序有一些限制,但它们在大多数情况下工作得很好。

要了解更多信息,请参阅jQuery文档。

更新:live()和die()在jQuery 1.7中已弃用。参见http://api.jquery.com/on/和http://api.jquery.com/off/了解类似的替换功能。

UPDATE2: live()早在jQuery 1.7之前就已经弃用了。对于1.7之前的jQuery 1.4.2+版本,请使用delegate()和undelegate()。live()示例($('button.someClass')。live('click', someFunction);)可以像这样使用delegate()重写:$(document).delegate('button.someClass', 'click', someFunction);


说到技巧和技巧,以及一些教程。我发现Jeffery Way的这些系列教程(“jQuery绝对初学者”视频系列)非常有用。

它针对那些刚接触jQuery的开发人员。他展示了如何用jQuery创建许多很酷的东西,比如动画,创建和删除元素等…

我从中学到了很多。他展示了如何简单地使用jQuery。 现在我喜欢它,我可以阅读和理解任何jQuery脚本,即使它很复杂。

这里有一个我喜欢的例子“调整文本大小”

1 - jQuery……

<script language="javascript" type="text/javascript">
    $(function() {
        $('a').click(function() {
            var originalSize = $('p').css('font-size'); // get the font size 
            var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable "originalSize"
            var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch

            $('p').css('font-size', number / 1.2 + unitOfMeasure);
            if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered
         });        
     });
</script>

2- CSS样式…

<style type="text/css" >
body{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}
.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}
</style>

2 - HTML……

<div class="box">
    <a href="#" id="larger">Larger</a> | 
    <a href="#" id="Smaller">Smaller</a>
    <p>
    In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods. 
    </p>
</div>

强烈推荐这些教程…

http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/


从集合中移除元素并保留可链性

考虑以下几点:

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

$("li").filter(function()
{
    var text = $(this).text();

    // return true: keep current element in the collection
    if (text === "One" || text === "Two") return true;

    // return false: remove current element from the collection
    return false;
}).each(function ()
{
    // this will alert: "One" and "Two"       
    alert($(this).text());
});

filter()函数的作用是:从jQuery对象中删除元素。在这种情况下:所有不包含文本“One”或“Two”的li-element将被删除。


优化复杂选择器的性能

当使用复杂的选择器时,查询DOM的一个子集可以极大地提高性能:

var subset = $("");

$("input[value^='']", subset);

(这是一个无耻的插头)

与其写重复的表单处理代码,你可以试试我写的这个插件,它通过添加表单相关的方法添加到jQuery的流畅API:

// elementExists is also added
if ($("#someid").elementExists())
  alert("found it");

// Select box related
$("#mydropdown").isDropDownList();

// Can be any of the items from a list of radio boxes - it will use the name
$("#randomradioboxitem").isRadioBox("myvalue");
$("#radioboxitem").isSelected("myvalue");

// The value of the item selected. For multiple selects it's the first value
$("#radioboxitem").selectedValue();

// Various, others include password, hidden. Buttons also
$("#mytextbox").isTextBox();
$("#mycheck").isCheckBox();
$("#multi-select").isSelected("one", "two", "three");

// Returns the 'type' property or 'select-one' 'select-multiple'
var fieldType = $("#someid").formElementType();

这个是给科比的。

考虑下面的代码片段:

// hide all elements which contains the text "abc"
$("p").each(function ()
{
    var that = $(this);

    if (that.text().indexOf("abc") > -1) that.hide();
});    

这里有一个简写……这大约是原来的两倍:

$("p.value:contains('abc')").hide();

似乎大多数有趣和重要的技巧都已经提到了,所以这一点只是一个小小的补充。

这个小技巧就是jQuery。每个(对象,回调)函数。每个人都可能使用jQuery.each(回调)函数来遍历jQuery对象本身,因为这很自然。jQuery。每个(对象,回调)实用程序函数迭代对象和数组。在很长一段时间里,除了不同的语法之外,我不知道它能做什么(我不介意写所有时髦的循环),我有点惭愧,直到最近我才意识到它的主要优点。

问题是,自从jQuery的循环体。每个(对象,回调)是一个函数,每次在循环中都获得一个新的作用域,这在循环中创建闭包时尤其方便。

换句话说,一个典型的常见错误是这样做的:

var functions = [];
var someArray = [1, 2, 3];
for (var i = 0; i < someArray.length; i++) {
    functions.push(function() { alert(someArray[i]) });
}

现在,当您调用函数数组中的函数时,您将得到三次警报,内容为undefined,这很可能不是您想要的。问题是只有一个变量i,而所有三个闭包都指向它。当循环结束时,i的最终值是3,somearray[3]是未定义的。你可以通过调用另一个函数来为你创建闭包。或者你使用jQuery实用工具,它基本上会为你做:

var functions = [];
var someArray = [1, 2, 3];
$.each(someArray, function(item) {
    functions.push(function() { alert(item) });
});

现在,当您调用这些函数时,您将得到三个内容为1、2和3的警报。

一般来说,没有什么是你自己不能做的,但拥有它是很好的。


更新:

只要在站点上包含这个脚本,您就会得到一个Firebug控制台,可以在任何浏览器中进行调试。虽然功能不全,但还是很有用的!吃完之后记得把它拿掉。

<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>

看看这个链接:

来自CSS技巧

更新: 我发现了一些新的东西;它是JQuery Hotbox。

JQuery轴承箱

谷歌在谷歌Code上托管了几个JavaScript库。从那里加载它可以节省带宽,而且加载速度很快,因为它已经被缓存了。

<script src="http://www.google.com/jsapi"></script>  
<script type="text/javascript">  

    // Load jQuery  
    google.load("jquery", "1.2.6");  

    google.setOnLoadCallback(function() {  
        // Your code goes here.  
    });  

</script>

Or

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

你也可以用它来判断图像何时完全加载。

$('#myImage').attr('src', 'image.jpg').load(function() {  
    alert('Image Loaded');  
});

firebug的"console.info",您可以使用它将消息和变量转储到屏幕上,而不必使用警告框。”控制台。Time”允许你轻松地设置一个计时器来包装一堆代码,并查看它需要多长时间。

console.time('create list');

for (i = 0; i < 1000; i++) {
    var myList = $('.myList');
    myList.append('This is list item ' + i);
}

console.timeEnd('create list');

在元素创建时定义属性

在jQuery 1.4中,你可以在创建元素时使用对象文字来定义属性:

var e = $("<a />", { href: "#", class: "a-class another-class", title: "..." });

... 你甚至可以添加样式:

$("<a />", {
    ...
    css: {
        color: "#FF0000",
        display: "block"
    }
});

这里有一个文档链接。


无用的模式

jQuery.noConflict();

运行此函数将$变量的控制权交还给第一个实现它的库。这有助于确保jQuery不会与其他库的$ object冲突。 通过使用这个函数,你将只能通过jQuery变量访问jQuery。例如,你过去做$("div p"),你现在必须做jQuery("div p")"。


“准备事件”的简称

显式和详细的方式:

$(document).ready(function ()
{
    // ...
});

速记:

$(function ()
{
    // ...
});

换行和可链性

当在集合上链接多个调用时…

$("a").hide().addClass().fadeIn().hide();

你可以用换行符增加可读性。是这样的:

$("a")
.hide()
.addClass()
.fadeIn()
.hide();

更改输入元素的类型

我在尝试更改已附加到DOM的输入元素的类型时遇到了这个问题。您必须克隆现有元素,在旧元素之前插入它,然后删除旧元素。否则就不行:

var oldButton = jQuery("#Submit");
var newButton = oldButton.clone();

newButton.attr("type", "button");
newButton.attr("id", "newSubmit");
newButton.insertBefore(oldButton);
oldButton.remove();
newButton.attr("id", "Submit");

异步each()函数

如果你有非常复杂的文档,在迭代过程中运行jquery each()函数会锁住浏览器,并且/或Internet Explorer弹出“是否要继续运行此脚本”消息,这个解决方案将会挽救你的一天。

jQuery.forEach = function (in_array, in_pause_ms, in_callback)
{
    if (!in_array.length) return; // make sure array was sent

    var i = 0; // starting index

    bgEach(); // call the function

    function bgEach()
    {
        if (in_callback.call(in_array[i], i, in_array[i]) !== false)
        {
            i++; // move to next item

            if (i < in_array.length) setTimeout(bgEach, in_pause_ms);
        }
    }

    return in_array; // returns array
};


jQuery.fn.forEach = function (in_callback, in_optional_pause_ms)
{
    if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default

    return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it
};

你可以使用它的第一种方式就像each():

$('your_selector').forEach( function() {} );

可选的第二个参数让你指定迭代之间的速度/延迟,这对动画可能很有用(下面的例子将在迭代之间等待1秒):

$('your_selector').forEach( function() {}, 1000 );

记住,因为这是异步工作的,你不能依赖于迭代在下一行代码之前完成,例如:

$('your_selector').forEach( function() {}, 500 );
// next lines of code will run before above code is complete

我为一个内部项目写了这篇文章,虽然我确信它可以改进,但它满足了我们的需要,所以希望你们中的一些人会觉得它有用。谢谢- - -


使用.stop(true,true)当触发一个动画防止它重复动画。这对于翻转动画特别有用。

$("#someElement").hover(function(){
    $("div.desc", this).stop(true,true).fadeIn();
},function(){
    $("div.desc", this).fadeOut();
});

在方法调用(如.append())中使用自动执行的匿名函数来遍历某些内容。例如:

$("<ul>").append((function ()
{
    var data = ["0", "1", "2", "3", "4", "5", "6"],
        output = $("<div>"),
        x = -1,
        y = data.length;

    while (++x < y) output.append("<li>" + info[x] + "</li>");

    return output.children();
}()));

我使用这种方法来迭代那些不适合跳出我的链接来构建的大而不舒服的东西。


在名称中增加行索引

下面是一个简单的方法来增加一个克隆的输入元素的行索引,如果你的输入元素名称包含一个像'0_row'这样的行索引:

$(this).attr('name', $(this).attr('name').replace(/^\d+/, function(n){ return ++n; }));

克隆元素的名称现在是'1_row'


像访问数组一样访问jQuery函数

添加/删除基于布尔值的类…

function changeState(b)
{
    $("selector")[b ? "addClass" : "removeClass"]("name of the class");
}

是…的简短版本。

function changeState(b)
{
    if (b)
    {
        $("selector").addClass("name of the class");
    }
    else
    {
        $("selector").removeClass("name of the class");
    }
}

这个用例并不多。尽管如此;我认为这很整洁:)

更新

为了防止您不是注释阅读类型,ThiefMaster指出toggleClass接受一个布尔值,该值决定是否应该添加或删除一个类。因此,就我上面的示例代码而言,这将是最好的方法……

$('selector').toggleClass('name_of_the_class', true/false);

尽可能使用过滤方法而不是伪选择器,这样jQuery就可以使用querySelectorAll(这比sizzle快得多)。考虑这个选择器:

$('.class:first')

同样的选择可以使用:

$('.class').eq(0)

哪个必须更快,因为初始选择'.class'是QSA兼容


无耻的宣传……jQuery模板插件:使用渲染函数实现复杂的逻辑

The new jQuery template plug-in is awesome. That being said, the double-curly brace template-tags are not exactly my cup of tea. In a more complex template the tags obscure the templates markup, and implementing logic past simple if/else statements is a pain. After messing around with the plug-in for a few hours, my head began to hurt from trying to distinguish the markup in my template from the millions of double curly braces. So I popped an aspirin and began work on an alternative


为折叠以上的元素添加一个选择器

作为jQuery的选择器插件

 $.extend($.expr[':'], {
 "aboveFold": function(a, i, m) {
   var container = m[3],
   var fold;
  if (typeof container === "undefined") {
     fold = $(window).height() + $(window).scrollTop();
  } else {
     if ($(container).length == 0 || $(container).offset().top == null) return false;
     fold = $(container).offset().top + $(container).height();
  }
  return fold >= $(a).offset().top;
 } 
});

用法:

$("p:aboveFold").css({color:"red"});

谢谢scottymac


从更基本、更高级的角度来看,您可以尝试通过编写自己的小框架来模拟jQuery的基本选择器机制(实际操作比听起来简单)。它不仅会不断地改进你的Javascript,还会帮助你理解为什么jQuery的$("#elementId")比$(". elementclass ")快很多倍,也比$("element#elementId")快很多倍(这可能在表面上与直觉相反)。

这也将迫使你学习面向对象的Javascript,这将帮助你以一种更模块化的方式组织你的代码,从而避免沉重的jQuery脚本块所带来的意大利面条式的代码性质。


访问iFrame元素 Iframes并不是大多数问题的最佳解决方案,但当你需要使用Iframes时,知道如何使用Javascript访问其中的元素是非常方便的。jQuery的contents()方法使这变得轻而易举,使我们能够在一行中加载iframe的DOM,就像这样:

$(function(){
    var iFrameDOM = $("iframe#someID").contents();
    //Now you can use <strong>find()</strong> to access any element in the iframe:

    iFrameDOM.find(".message").slideUp();
    //Slides up all elements classed 'message' in the iframe
});


HTML5数据属性支持,在类固醇!

数据函数之前已经提到过。有了它,您就可以将数据与DOM元素关联起来。

最近,jQuery团队增加了对HTML5自定义data-*属性的支持。似乎这还不够;他们用类固醇强制输入数据函数,这意味着你可以直接在标记中以JSON的形式存储复杂的对象。

HTML:

<p data-xyz = '{"str": "hi there", "int": 2, "obj": { "arr": [1, 2, 3] } }' />

JavaScript:

var data = $("p").data("xyz");

data.str // "hi there"
typeof data.str // "string"

data.int + 2 // 4
typeof data.int // "number"

data.obj.arr.join(" + ") + " = 6" // "1 + 2 + 3 = 6"
typeof data.obj.arr // "object" ... Gobbles! Errrghh!

“以”结尾的元素选择器对于ASP非常有用。NET web表单开发,因为你不需要担心前面的ctl00的愚蠢:

$("[id$='txtFirstName']");

正如注释中所指出的,如果不小心使用,这个选择器(与任何抽象层一样)可能会很慢。更倾向于将选择器作用于包含元素的范围,例如:

$(".container [id$='txtFirstName']");

减少遍历所需元素的数量。

jQuery文档


绑定到事件并立即执行事件处理程序:

$('selector').bind('change now', function () { // bind to two events: 'change' and 'now'
    // update other portions of the UI
}).trigger('now'); // 'now' is a custom event

这就像

function update() {
    // update other portions of the UI
}
$('selector').change(update);
update();

但是不需要创建单独的命名函数。