将元素中包含的内容与数组一起添加
add what contains in element along with array
我正在尝试添加每个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);
});
相关文章:
- 高亮显示与数组字符串一起使用时文本插件中断
- 将推入式数组与for一起使用..在..循环中
- 将代理与纯数组一起使用
- 将数组原型函数与非数组一起使用
- 将 JavaScript new 关键字与可变长度参数数组一起使用
- 如何将Math.max与对象数组一起使用
- 将拼接与字符串数组一起使用
- 将Slice与Knockout创建的数组一起使用's映射插件
- 将元素中包含的内容与数组一起添加
- 尝试将IF语句与数组一起使用时遇到问题
- RegExp用于验证不与数组一起工作的网站URL
- 正在尝试将Google Visualization API中的addRows()与数组数组一起使用JavaScript/
- Javascript数组一起改变
- jQuery map不能与json数组一起工作
- D3.js直方图不能与每个箱子的总频率数组一起工作
- MongoDB将$in与对象数组一起使用
- 如何将fullcalendar addeventsource与数组一起使用
- 如何将 _.each 与对象或多维数组一起使用
- encodeuriccomponent不能与数组一起工作
- AngularJS:如何将ngRepeat指令与数组和子数组一起使用