2012-02-07 91 views
4

我试图添加每个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 

我该如何得到这个结果?

回答

2

看起来你正在寻找

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()

1

只需使用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('')); 
}); 
1

你行

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

应该像这样:

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

虽然,这使得两个相同的电话$(this),所以你可能会缺点IDER缓存:

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

Working JSFiddle

text

说明:获取每个元素的组合的文本内容集合中匹配的元素,包括其后代。

docs

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