JQuery 通过类名获取所有元素

在学习 javscript 和 jquery 的过程中,翻遍了 google 的页面,但似乎不能得到这个工作。基本上,我试图收集 innerhtml 类,jquery 似乎比普通的 javascript 建议,成为一个 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>

这样,只有第一个类显示在 document.write 下面。我怎样才能像第一个第二个第三个第三个第一个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个第三个?我的最终目标是让他们看到逗号是分开的就像第一块,第二块,第三块,第四块。谢谢,提出了一大堆相关问题,但似乎没有一个是这么简单的。

220196 次浏览

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.

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

With the code in the question, you're only directly interacting with the first of the four entries returned by that selector.

Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/

I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>


<body>
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>


<div id="outige"></div>
<script>
// using the $ prefix to use the "jQuery wrapped var" convention
var i, $mvar = $('.mbox');


// convenience method to display unprocessed html on the same page
function logit( string )
{
var text = document.createTextNode( string );
$('#outige').append(text);
$('#outige').append("<br>");
}


logit($mvar.length);


for (i=0; i<$mvar.length; i++)    {
logit($mvar.eq(i).html());
}
</script>
</body>


</html>

Output from logit calls (after the initial four div's display):

4
Block One
Block Two
Block Three
Block Four

to get the input value you can do something like this:

 var allvendorsList = $('.vendors').map(function () {
return this.value;
}).get();