使用Jquery,我想将具有特定类的所有元素的内容放入变量中。这是一个例子:
<div class="foo">
<div class="bar"><p>First set of text</p></div>
<div class="bar"><p>Second set of text</p></div>
<div class="bar"><p>Third set of text</p></div>
<div class="bar"><p>N set of text</p></div>
</div>
我想将所有带有“ bar”类的div元素的内容放入一个名为“ full”的变量中。我已经尝试了以下代码,但是显然只能抓住第一个div。
var full = $( ".bar" ).html();
我希望我的字符串变量的内容是
"<p>First set of text</p><p>Second set of text</p><p>Third set of text</p><p>N set of text</p>"
如果尝试在互联网上查找但找不到答案。我当时正在考虑使用.each方法,但是我的几次尝试都效果不佳。任何的想法?
谢谢!
您正确使用.each()
:
var full = '';
$('.bar').each(function () {
full += $.trim($(this).html());
})
console.log(full);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句