JQuery按类名获取所有元素
在学习javscript和jquery的过程中,经历了谷歌的网页,但似乎无法让这个工作。基本上我正在尝试收集类的innerhtml,jquery似乎比普通的javascript建议,写入document.write。
in the process of learning javscript and jquery, went through pages of google but can't seem to get this working. Basically I'm trying to collect innerhtml of classes, jquery seems to be suggested than plain javascript, into a document.write.
这是迄今为止的代码;
Here's the code so far;
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<script>
var mvar = $('.mbox').html();
document.write(mvar);
</script>
这样,只有第一个类显示在document.write下。我怎么能像Block OneBlock TwoBlock Three一样展示它们?我的最终目标是向他们展示逗号分隔,如Block Four,Block Two,Block Three,Block Four。谢谢,一堆相关的问题出现了但似乎没有这么简单。
With this, only the first class shows under document.write. How can I show it all together like Block OneBlock TwoBlock Three? My ultimate goal with this is to show them comma seperated like Block One, Block Two, Block Three, Block Four. Thanks, bunch of relevant questions come up but none seem to be this simple.
一种可能的方法是使用 .map()
方法:
One possible way is to use .map()
method:
var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
DEMO: http://jsfiddle.net/Y4bHh/
NB 请不要使用文件撰写
。出于测试目的, console.log
是最好的方法。
N.B. Please don't use document.write
. For testing purposes console.log
is the best way to go.