我有HTML文字,如:
401 Unauthorized
我希望得到这样的结果:
C1:text1 text2 text3 + text18 text19 text20
C2:text8 text9 text10
表示按span分组文本 我怎样才能在Javascript中执行此操作
答案 0 :(得分:2)
如果你想在jquery中完成它(因为你已经标记了jquery),请使用它:
var spanText;
$(".c1").each(function(){
spanText+=$(this).text();
});
console.log(spanText);
答案 1 :(得分:1)
var t1;
$('.c1').each(function(){
t1 += $(this).text();
});
var t2;
$('.c2').each(function(){
t2 += $(this).text();
});
console.log('C1: ' + t1);
console.log('C2: ' + t2);

<span class="c1" > text1 text2 text3 </span>
<span class="c2" > text8 text9 text10 </span>
<span class="c1" > text18 text19 text20 </span>
&#13;
答案 2 :(得分:1)
Vanilla JS:
// pass in a selector
function getText(selector) {
// grab the elements specified by the selector
var spans = document.querySelectorAll(selector);
// return the text from each element
// [].slice.call is used because `spans` is only "array-like"
// and we need to convert it to a proper array to make use of `map`
return [].slice.call(spans).map(function (el) {
return el.innerHTML;
}).join('');
}
getText('span.c1'); // text1 text2 text3 text18 text19 text20
getText('span.c2'); // text8 text9 text10
答案 3 :(得分:1)
这是一个通用的解决方案,如果有更多c1
和c2
:
var cs = $('span[class^="c"]');
var r = {};
cs.each(function() {
var e = $(this);
if (!r[e.attr('class')]) {
r[e.attr('class')] = '';
}
r[e.attr('class')] += e.text();
});
alert (r.c1);
alert (r.c2);
<强>演示强>