Alternative to jQuery each() - self educational qu

2019-08-05 01:57发布

问题:

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...

回答1:

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



回答2:

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 ,


回答3:

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.



回答4:

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.