问题
I'm attempting to use .text() on multiple (unknown number of) elements on a page.
Consider:
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
$('.myClass').text();
Will return the first element's text "element1".
I came across the following while looking around:
$('.myClass').each(function(index, obj)
{
// do something
});
However, this simply query returns each full elements like:
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
I need to return all element's text such as:
"element1" "element2" "element3"
Thanks!
回答1:
var x =[];
$('.myClass').each(function(index, obj)
{
x.push($(this).text());
});
console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
回答2:
You can use map()
to retrieve a specific property of a group of elements and place them in an array:
var textValues = $('.myClass').map(function() {
return $(this).text();
}).get();
From there you can work with the array to create the string as you need, for example, using join()
:
console.log(textValues.join(', ')); // = 'element1, element2, element3'
var textValues = $('.myClass').map(function() {
return $(this).text();
}).get();
console.log(textValues.join(', ')); // = 'element1, element2, element3'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
回答3:
Simply concat the text inside .each
. Here is a DEMO
Here is modified jQuery:
$(function() {
var names = '';
$('.myClass').each(function(index, obj) {
names += $(this).text() +',';
});
alert(names);
});
回答4:
Make use of $(this)..!
var string = null;
$('.myClass').each(function(index, obj){
// do something
string += $(this).text();
});
来源:https://stackoverflow.com/questions/28559846/jquery-text-multiple-elements-same-class