Jquery 计算动态创建的元素数

Jquery 计算动态创建的元素数,jquery,Jquery,我已经使用下面的代码动态地用一个span换行字符 $("span.count").children().andSelf().contents().each(function(){ if (this.nodeType == 3) { var $this = $(this); $this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));

我已经使用下面的代码动态地用一个span换行字符

    $("span.count").children().andSelf().contents().each(function(){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
    }
});
$(“span.count”).children()和self().contents().each(function()){
if(this.nodeType==3){
var$this=$(this);
$this.replaceWith($this.text().replace(/(\w)/g,“$&”);
}
});
我正在尝试(完成后)计算包装元素的数量,以便根据数量将类附加到它们的容器中。我尝试过各种方法(我认为我的问题是试图计算动态创建的内容),但似乎都不起作用。以下是我目前的情况:

    var n = $("span.count").live().children().length;
if (n < 3) {
    $(".counter").addClass("four");
}
var n=$(“span.count”).live().children().length;
if(n<3){
$(“.counter”).addClass(“四”);
}

任何帮助都将不胜感激。

您可以在插入的
中添加一个类,然后计算该类的数量。

您不能以您尝试的方式使用
.live()
。它现在已被弃用,只用于委托事件处理,不用于DOM更改。如果将一个类添加到要添加的范围中,则可以简单地计算它:

$("span.count").children().andSelf().contents().each(function(){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/(\w)/g, "<span class="letter">$&</span>"));
    }
});

var cnt = $(".letter").length;
$(“span.count”).children()和self().contents().each(function()){
if(this.nodeType==3){
var$this=$(this);
$this.replaceWith($this.text().replace(/(\w)/g,“$&”);
}
});
var cnt=$(“.letter”).长度;
或者,您可以使用自定义替换功能并在每次替换时增加一个计数器:

var spanCnt = 0;
$("span.count").children().andSelf().contents().each(function(){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/(\w)/g, function(match) {
            ++spanCnt;
            return("<span>" + match + "</span>");
        }));
    }
});
var spanCnt=0;
$(.span.count”).children()和self().contents().each(function()){
if(this.nodeType==3){
var$this=$(this);
$this.replaceWith($this.text().replace(/(\w)/g,函数(匹配){
++spanCnt;
返回(“+match+”);
}));
}
});