将元素中包含的内容与数组一起添加

add what contains in element along with array

本文关键字:数组 一起 添加 元素 包含      更新时间:2023-09-26

我正在尝试添加每个span的内容以及title属性中的值。

<div id="group-wrap" class="group">
    <span class="lbracket" title="&f">(</span>
    <span class="grouptitle" title="&f"> Group </span>
    <span class="rbracket" title="&f">) </span>
    <span class="username" title="&f"> Username </span>
    <span class="col" title="&f">:</span>
    <span class="text" title="&f"> Helo There! </span>
</div>

以下是我目前所拥有的:

var str = [];
    $('#group-wrap span').each(function(){
        str.push($(this).attr('title'));
    });
    alert(str.join(''));
});

http://jsfiddle.net/B9QeK/3/

输出为&f&f&f&f&f(每个标题属性的值),但预期输出具有值,加上跨度中的内容。属性的值应该附加在内容之前。

&f(&fGroup&f)&fUsername: &f text

我怎样才能得到这个结果?

看起来您正在寻找

str.push( this.getAttribute('title'), this.textContent || this.text );

出于性能原因,不应该为每一次迭代重新创建jQuery对象。更好的是,不要使用jQuery来接收这些值。

JSFiddle

顺便说一下,您可以使用jQuerys .map()来做得更优雅一点:

jQuery(function($){
    var str = $('#group-wrap span').map(function(){
        return this.getAttribute('title') + this.textContent || this.text;
    }).get();
    alert(str.join(''));
});

JSFiddle

参考:.map()

jQuery(function($){
    var str = [];
    $('#group-wrap span').each(function(){
        str.push($(this).attr('title') + $(this).text());
    });
    alert(str.join(''));
});

工作JSFiddle

text:

描述:获取匹配元素集中每个元素的组合文本内容,包括它们的子元素。

docs

只需使用text方法即可获得每个span:的文本内容

var str = [];
    $('#group-wrap span').each(function(){
        //Push value of title attribute and text content into array:
        str.push($(this).attr('title') + $(this).text());
    });
    alert(str.join(''));
});

您的线路

str.push($(this).attr('title'));

应该看起来像:

str.push($(this).attr('title') + $(this).text());

尽管如此,这是在进行两个相同的调用$(this),因此您可能会考虑缓存:

var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
    $('#group-wrap span').each(function(){
        str+=$(this).attr('title')+$(this).text();
    });
    alert(str);
});