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.

以下是到目前为止的代码;

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

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.

推荐答案

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/

N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

Jquery相关问答推荐

jQuery在localStorage时将类添加到正文

Flask,如何为ajax调用返回成功状态码

jQuery在点击函数后获取
  • 元素的id/value
  • 提高 jQuery Select 器性能的好方法?

    $.post 和 $.ajax 之间的区别?

    提交前添加 POST 参数

    jQuery ajax 调用默认超时值

    在 jQuery UI Datepicker 中禁用future 日期

    纯css关闭按钮

    jQuery Mobile:动态添加内容的标记增强

    jQuery ajax() 使用成功、错误和完成与 .done()、.fail() 和 always()

    jQuery getJSON 将结果保存到变量中

    使用 jQuery 获取选定的选项 id

    如何推迟内联 Javascript?

    JQuery - 按值查找单选按钮

    在未实现接口 FormData 的对象上调用附加

    如何获得两个日期对象之间的小时差?

    在jQuery中,当它们都具有相同的名称时,如何获取单选按钮的值?

    jQuery中的wait()或sleep()函数?

    为什么我应该创建异步 WebAPI 操作而不是同步操作?