jQuery的每个这个 [英] jQuery each this

查看:123
本文介绍了jQuery的每个这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var slides = $(".promo-slide");
slides.each(function(key, value){
    if (key == 1) {
        this.addClass("first");
    }
});

为什么会出现错误提示:

Why do I get an error saying:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'

从上面的代码开始?

推荐答案

在jQuery回调函数中,this引用DOM对象,而不是jQuery对象.

Inside jQuery callback functions, this refers to a DOM object, not a jQuery object.

var slides = $(".promo-slide");
slides.each(function(key, value){
    if (key == 0) { // NOTE: the key will start to count from 0, not 1!
        $(this).addClass("first");
//------^^----^       
    }
});

但是:就您而言,这更容易:

BUT: In your case, this is easier:

$(".promo-slide:first").addClass("first");

顺便说一句,我发现对包含jQuery对象的变量加上$前缀是有用的约定:

As an aside, I find it a useful convention to prefix variables that contain a jQuery object with a $:

var $slides = $(".promo-slide");
$slides.each( /* ... */ );

这篇关于jQuery的每个这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆