开发者

JQuery: How to get "item1, item2" from this HTML page?

I want to get "item 1, item 2" out of this simple HTML page:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<body>
<ul id="mylist">
  <li>item 1</li>
  <li>item 2</li>
</ul>
</body>
</html>

Here is what I tried on Chromium's JavaScript console:

开发者_StackOverflow社区
> var a = $("#mylist").children().map(function(index,element){ return $(element).text(); });
> a
["item 1", "item 2"]
> a.join(", ")
TypeError: Object [object Object] has no method 'join'

If a was an array object, the join would work:

> ["item 1", "item 2"].join(", ")
"item 1, item 2"

But it is not, so how to join?


You need to call .get() to get a normal array object back.

a.get().join(", ")

http://api.jquery.com/get/


You just missed the .toArray() part

var a = $("#mylist").children().map(function(index,element){ return $(element).text(); }).toArray().join(", ");


The each() way:

var results = [];
$("#mylist li").each(function() { 
    results.push($(this).text()); 
});
results = results.join(", ");


Here are two possibilities:

1:

var a = $("#mylist").children().map(function(index,element){ return $(element).text(); });  
var string = ""
for (var i = 0; i < a.length - 1; i++) string += a[i] + ", ";
string += a[a.length - 1];

2:

var a = $("#mylist").children().map(function(index,element){ return $(element).text(); }); 
var b = [];
for (var i = 0; i < a.length; i++) b.push(a[i]);
b.join(", ");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜