Alternative to jQuery each() - self educational qu

2019-08-05 02:17发布

Looking at this

get value of inside a tag with jQuery.?

<span>
 <b>hi_1</b>
 <b>hi_2</b>
 <b>hi_3</b>
 <b>hi_4</b>
<span>

where the question was to get a comma delimited string of the tag contents

the solution is a push inside an each.

Is there a shorter (and possibly faster) way using for example

$("span b").text().join(",") which of course does not work since text() does not return an array...

UPDATE:

the "bug report" (feature request) posted by artyom had this rather interesting snippet

var x = $("span b").map(function() {
  return $(this).text();
}).toArray().join(", "); 

which is similar to BrokenGlass' solution but shorter...

http://jsfiddle.net/mplungjan/M42Qx/

I prefer the toArray one...

4条回答
不美不萌又怎样
2楼-- · 2019-08-05 02:31

There was a bug report about adding this functionality to the text() method, which was closed with worksforme resolution after a few ways to do this were provided.

查看更多
霸刀☆藐视天下
3楼-- · 2019-08-05 02:34

You could use map(), but I doubt this would be faster since you have to convert from jQuery object to array and back to jQuery object:

var results = $("b").get()
                    .map(function(e) { return $(e).text();})
                    .join(",");
alert(results);

jsFiddle link

查看更多
一纸荒年 Trace。
4楼-- · 2019-08-05 02:41

This may be cheating, but since there isn't any text outside of the <b> tags, you can simply use $('span').text() to grab the inner text of the <span> and work with that instead...

$.trim($('span').text()) // Trim newlines near <span> and </span> tags
 .replace(/\s+/g, ', '); // Replace all other whitespace between <b></b> with ,
查看更多
▲ chillily
5楼-- · 2019-08-05 02:49

The only option that came to my mind, and far less impressive than @BoltClock's alternative, is to use filter():

var values = [];
$('b').filter(
    function(){
        return values.push($(this).text());
    });
alert(values);

JS Fiddle demo.

And this isn't that much different to a solution using each(), since it more or less does the same thing.

查看更多
登录 后发表回答