Home > CMS Tutorial > WordPress > body text

15 New Features You Must Know: jQuery 1.4 Released

王林
Release: 2023-08-30 22:53:07
Original
773 people have browsed it

jQuery 1.4 was recently released. This is not just a maintenance release as some have speculated; 1.4 contains many new features, enhancements, and performance improvements! This article describes new features and enhancements that you may find beneficial.

You can download jQuery 1.4 now here: http://code.jquery.com/jquery-1.4.js

1. Passing properties to jQuery(...)

Prior to 1.4, jQuery supported adding attributes to a collection of elements through the useful "attr" method, which could be passed the attribute name and value, or an object specifying multiple attributes. jQuery 1.4 added support for passing a property object as the second argument to the jQuery function itself when creating an element.

Suppose you need to create an anchor element with multiple attributes. For 1.4, it's as simple as this:

jQuery('<a/>', {
    id: 'foo',
    href: 'http://google.com',
    title: 'Become a Googler',
    rel: 'external',
    text: 'Go to Google!'
});
Copy after login

You may have noticed the "text" attribute - you may be wondering what it does there, after all anchors don't have a "text" attribute! Well, jQuery 1.4 uses it's own method when you pass certain properties. Therefore, the "text" attribute specified above will cause jQuery to call the ".text()" method, passing "Go to Google!" as its only argument.

A better practical example:

jQuery('<div/>', {
    id: 'foo',
    css: {
        fontWeight: 700,
        color: 'green'
    },
    click: function(){
        alert('Foo has been clicked!');
    }
});
Copy after login

The "id" is added as a regular attribute, but the "css" and "click" attributes trigger a call to each corresponding method. The above code, before version 1.4, should be written like this:

jQuery('<div/>')
    .attr('id', 'foo')
    .css({
        fontWeight: 700,
        color: 'green'
    })
    .click(function(){
        alert('Foo has been clicked!');
    });
Copy after login

Learn more about jQuery(...)

2. All "until"!

Three new methods were added to the DOM traversal library in

1.4, "nextUntil", "prevUntil" and "parentsUntil". Each of these methods traverses the DOM in some direction until the passed selector is satisfied. So, let's say you have a list of fruits:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>

    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>
Copy after login
Copy after login

You want to select all items after "Apple", but you want to stop after reaching "Strawberry". It couldn’t be simpler:

jQuery('ul li:contains(Apple)').nextUntil(':contains(Pear)');
// Selects Banana, Grape, Strawberry
Copy after login

Learn more about: prevUntil, nextUntil, parentsUntil

3. Binding multiple event handlers

Instead of chaining a bunch of event binding methods together, you can lump them all into the same call, like this:

jQuery('#foo).bind({
    click: function() {
        // do something
    },
    mouseover: function() {
        // do something
    },
    mouseout: function() {
        // do something
    }
})
Copy after login

This also applies to ".one()".

Learn more about .bind(...)

4. Loose

for each attribute

You can now define a different easing function for each property you want to animate, instead of just one easing function for a single animation. jQuery includes two easing functions: swing (default) and Linear. For the others, you need to download them separately!

To specify an easing function for each property, simply define the property as an array, the first value being the value you want to animate for that property, and the second value being the easing function to use:

jQuery('#foo').animate({
    left: 500,
    top: [500, 'easeOutBounce']
}, 2000);
Copy after login

See the actual effect of this code!

You can also define the easing function for each property in the optional options object as a property name-value pair in the "specialEasing" object:

jQuery('#foo').animate({
    left: 500,
    top: 500
}, {
    duration: 2000,
    specialEasing: {
        top: 'easeOutBounce'
    }
});
Copy after login

Editor's Note - The author of this article, James Padolsey, is very humble. This new feature was his idea!

Learn more about easing by attribute

5. New live event!

jQuery 1.4 adds support for delegates "Submit", "Change", "Focus" and "Blur" strong>" event. In jQuery, we use the ".live()" method to delegate events. When you have to register event handlers on many elements, and over time new ones may be added This is useful when working with elements (using ".live()" is cheaper than constantly rebinding).

But, be careful! If you want to delegate the "focus" and "blur" events you must use the event names "focusin" and "focusout"!

jQuery('input').live('focusin', function(){
    // do something with this
});
Copy after login

6. Control function context

jQuery 1.4 provides a new "proxy" function under the jQuery namespace. The function accepts two parameters, either "scope" and the method name, or the function and the expected scope. JavaScript’s “this” keyword can be difficult to master. Sometimes you don't want it to be an element, but an object you created previously.

For example, here we have a "app" object, which has two properties, a "clickHandler" method and a configuration object:

var app = {
    config: {
        clickMessage: 'Hi!'
    },
    clickHandler: function() {
        alert(this.config.clickMessage);
    }
};
Copy after login

The "clickHandler" method, when called like "app.clickHandler()", will have "app" as its context, which means Using the "this" keyword will allow it to access "app". If we simply call:

app.clickHandler(); // "Hi!" is alerted
Copy after login

Let's try binding it as an event handler:

jQuery('a').bind('click', app.clickHandler);
Copy after login

当我们单击锚点时,它似乎不起作用(没有任何警报)。这是因为 jQuery(以及大多数理智的事件模型)默认情况下会将处理程序的上下文设置为目标元素,也就是说,刚刚单击的元素将可以通过“this”访问。但我们不希望这样,我们希望将“this”设置为“app”。在 jQuery 1.4 中实现这一点再简单不过了:

jQuery('a').bind(
    'click',
    jQuery.proxy(app, 'clickHandler')
);
Copy after login

现在,每当点击锚点时,“嗨!”将会收到警报!

代理函数返回函数的“包装”版本,并将“this”设置为您指定的任何内容。它在其他上下文中也很有用,例如将回调传递给其他 jQuery 方法或插件。

了解有关 jQuery.proxy

7。延迟动画队列

您现在可以向动画队列添加延迟。事实上,这适用于任何队列,但其最常见的用例可能是“fx”队列。这允许您在动画之间暂停,而不必混乱回调和调用“setTimeout”。 “.delay()”的第一个参数是您想要延迟的毫秒数。

jQuery('#foo')
    .slideDown() // Slide down
    .delay(200) // Do nothing for 200 ms
    .fadeIn(); // Fade in
Copy after login

如果您想要延迟默认“fx”队列以外的队列,则需要将队列名称作为第二个参数传递给“.delay()”。

了解更多关于 .delay(…)

8。检查元素是否某物

jQuery 1.4 可以轻松检查元素(或集合)“.has()”是否有某些内容。这相当于 jQuery 的选择器过滤器“:has()”的编程方式。此方法将选择当前集合中至少包含一个符合传递选择器的元素的所有元素。

jQuery('div').has('ul');
Copy after login

这将选择包含 UL 元素的所有 DIV 元素。在这种情况下,您可能只使用选择器过滤器(“:has()”),但是当您需要以编程方式过滤集合时,此方法仍然有用。

jQuery 1.4 还揭示了 jQuery 命名空间下的“contains”函数。这是一个接受两个 DOM 节点的低级函数。它将返回一个布尔值,指示第二个元素是否包含在第一个元素中。例如

jQuery.contains(document.documentElement, document.body);
// Returns true - <body> is within <html>
Copy after login

阅读更多内容:.has(...), jQuery.contains(...)

9。展开元素!

我们使用“.wrap()”方法已经有一段时间了。 jQuery 1.4 添加了“.unwrap()”方法,其作用完全相反。如果我们假设以下 DOM 结构:

<div>
    <p>Foo</p>
</div>
Copy after login

我们可以像这样展开段落元素:

jQuery('p').unwrap();
Copy after login

生成的 DOM 结构将是:

<p>Foo</p>
Copy after login

本质上,此方法只是删除任何元素的父元素。

了解更多关于 .unwrap(…)

10。删除元素而不删除数据

新的“<strong>.detach()</strong>”方法允许您从 DOM 中删除元素,与“.remove()”方法非常相似。这种新方法的主要区别在于它不会破坏 jQuery 在该元素上保存的数据。这包括通过“.data()”添加的数据以及通过 jQuery 事件系统添加的任何事件处理程序。

当您需要从 DOM 中删除元素,但您知道稍后需要将其添加回来时,这会很有用。其事件处理程序和任何其他数据都将保留。

var foo = jQuery('#foo');

// Bind an important event handler
foo.click(function(){
    alert('Foo!');
});

foo.detach(); // Remove it from the DOM

// … do stuff

foo.appendTo('body'); // Add it back to the DOM

foo.click(); // alerts "Foo!"
Copy after login

了解有关 .detach(...)

11。索引(...)增强功能

jQuery 1.4 为您提供了两种使用“.index()”方法的新方法。以前,您只能传递一个元素作为其参数,并且您希望返回一个数字,指示该元素在当前集合中的索引。

现在不传递任何参数会返回元素在其同级元素中的索引。因此,假设以下 DOM 结构:

<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Grape</li>

    <li>Strawberry</li>
    <li>Pear</li>
    <li>Peach</li>
</ul>
Copy after login
Copy after login

当单击一个列表项时,您想要找出被单击元素在所有其他列表项中的索引。很简单:

jQuery('li').click(function(){
    alert( jQuery(this).index() );
});
Copy after login

jQuery 1.4 还允许您指定一个选择器作为“.index()”的第一个参数,这样做将为您提供从该选择器生成的集合中当前元素的索引。

您应该注意,此方法返回的是一个整数,如果在文档中找不到传递的选择器/元素,它将返回 -1。

了解更多关于 .index(…)

12。 DOM 操作方法接受回调

大多数 DOM 操作方法现在支持传递函数作为唯一参数(或第二个参数,在“.css()”和“.attr()”的情况下)。此函数将在集合中的每个元素上运行,以确定应用作该方法的实际值的内容。

以下方法具有此功能:

  • 之后
  • 之前
  • 追加
  • 前置
  • 添加类
  • 切换类
  • 删除类
  • 包裹
  • 包裹所有
  • 包裹内部
  • 文本
  • 替换为
  • CSS
  • 属性
  • html

在回调函数中,您可以通过“this”访问集合中的当前元素,并通过第一个参数访问其索引。

jQuery('li').html(function(i){
    return 'Index of this list item: ' + i;
});
Copy after login

此外,使用上述某些方法,您还将获得第二个参数。如果您调用 setter 方法(例如“.html()”或“.attr('href)”),您将可以访问当前值。例如

jQuery('a').attr('href', function(i, currentHref){
    return currentHref + '?foo=bar';
});
Copy after login

如您所见,使用“.css()”和“.attr()”方法,您可以将该函数作为第二个参数传递,因为第一个参数将用于命名您想要更改的属性:

jQuery('li').css('color', function(i, currentCssColor){
    return i % 2 ? 'red' : 'blue';
});
Copy after login

13。确定对象的类型

jQuery 1.4 添加了两个新的辅助函数(直接存储在 jQuery 命名空间下),可帮助您确定正在处理的对象类型。

首先,有“isEmptyObject”,该函数返回一个布尔值,指示传递的对象是否为空(缺乏属性 - 直接继承)。其次,“isPlainObject”,它将返回一个布尔值,指示传递的对象是否是纯 JavaScript 对象,即通过“{}”或“new Object()”创建的对象。< /p>

jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({foo:1}); // false

jQuery.isPlainObject({}); // true
jQuery.isPlainObject(window); // false 
jQuery.isPlainObject(jQuery()); // false
Copy after login

了解更多: isPlainObject(...), isEmptyObject(...)

14。最近的(...)增强功能

jQuery 的“.closest()”方法现在接受选择器数组。当您想要遍历元素的祖先,查找(多个)具有某些特征的最接近元素时,这非常有用。

此外,它现在接受上下文作为第二个参数,这意味着您可以控制 DOM 遍历的距离或距离。这两个增强功能都适用于罕见的用例,但它们在内部使用时效果很好!

了解更多关于 .closest(…)

15。新活动! focusIn 和 focusOut

如上所述,要委托“focus”和“blur”事件,您必须使用这些新事件,称为“focusin”和“focusout”。这些事件允许您在元素或元素的后代获得焦点时采取操作。

jQuery('form')
    .focusin(function(){
        jQuery(this).addClass('focused');
    });
    .focusout(function(){
        jQuery(this).removeClass('focused');
    });
Copy after login

您还应该注意,这两个事件都不会传播(“冒泡”);他们被俘虏了。这意味着最外层(祖先)元素将在因果“目标”元素之前被触发。

了解有关 focusInfocusOut 事件的更多信息。

享受 jQuery 1.4,迄今为止最受期待、功能最丰富、性能最佳的 jQuery 版本!

嗯,就是这样!我已尽力涵盖我认为会对您产生影响的变化!

如果您还没有看过,您应该查看“jQuery 14 天”,这是一场精彩的在线活动,标志着 jQuery 1.4 的发布以及 jQuery 的四周年生日!

并且不要忘记查看新的 API 文档

编写 Plus 教程

您知道吗,为我们编写 PLUS 教程和/或截屏视频最多可赚取 600 美元? 我们正在寻找有关 HTML、CSS、PHP 和 JavaScript 的深入且编写良好的教程。如果您有能力,请通过 nettuts@tutsplus.com 联系 Jeffrey。

请注意,实际报酬将取决于最终教程和截屏视频的质量。

15个你必须了解的新功能:jQuery 1.4发布
  • 在 Twitter 上关注我们,或订阅 Nettuts+ RSS Feed 以获取网络上最好的 Web 开发教程。

The above is the detailed content of 15 New Features You Must Know: jQuery 1.4 Released. 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!