jQuery addClass()到append()后生成的元素 [英] jQuery addClass() to element generated after append()

查看:58
本文介绍了jQuery addClass()到append()后生成的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为新添加的DIV添加一个类而不使用类似的东西:

I am trying to add a class to a newly appended DIV without using something like:

t.y.append('<div class="lol'+i+'"></div>');

以下是我正在尝试做的更好的例子:

Here's a better example of what I'm trying to do:

var t = this;

$(this.x).each(function(i, obj) {
    //append new div and add class too <div></div>
    t.y.append('<div></div>').addClass('lol'+i);
});

页面加载HTML看起来像:

Page load HTML looks like:

<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
    <div></div>
    <div></div>
    <div></div>
</div>


推荐答案

当您通过 .append ,它不会改变jQuery对象的上下文。

When you append an element through .append, it doesn't change the context of the jQuery object.

你可以这样写:

$('< div>< / div>')。appendTo(ty).addClass('lol'+ i);

$('< div>< / div> ;')。addClass('lol'+ i).appendTo(ty);

(这些都做同样的事情,只是在不同的顺序,第二个可能更清楚)

(these both do the same thing, simply in different orders, the second possibly being more clear)

jQuery对象的上下文将是新创建的div。

the context of the jQuery object will be the newly created div.

这篇关于jQuery addClass()到append()后生成的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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