JQuery按类名获取所有元素 [英] JQuery get all elements by class name

查看:763
本文介绍了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.

这篇关于JQuery按类名获取所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆