开发者

Is it possible to convert this jquery chain returning a string into an array without a separate iteration?

开发者 https://www.devze.com 2023-01-31 20:45 出处:网络
I have a HTML snippet like the following <tr class=\"new\"> <td> <input name=\"id\" type=\"checkbox\"/>

I have a HTML snippet like the following

<tr class="new">
<td>
   <input name="id" type="checkbox"/>
   <span>9</span>
</td>
<td> // Other Stuff... </td>
</tr>
// other table rows
<tr class="new">
<td>
   <input name="id" type="checkbox"/>
   <span>12</span>
</td>
开发者_如何学运维<td> // Other Stuff... </td>
</tr>

CURRENTLY, a .find('.new').find('input[name="id"]:checked').next().text().trim(); gives me a string like "912".

Is there anyway I can get back an array like [9,12] or ["9","12"] without having to explicitly iterate through the list of inputs returned back by the .find snippet? I am open to changing the query in order to avoid an iteration.


You're looking for jQuery's map function:

$(...).find('.new input[name="id"]:checked')
      .next()
      .map(function() { return parseInt($.trim($(this).text(), 10); })
      .get()


You can use .map(), like this:

var arr = $('.new input[name="id"]:checked + span').map(function() {
            return $.trim((this).text());
          }).get();

If you want an array of numbers, just add a +, like this:

var arr = $('.new input[name="id"]:checked + span').map(function() {
            return +$.trim((this).text());
          }).get();


You could do this:

myArray = new Array();

.find('.new').find('input[name="id"]:checked').each(function(){
    myArray.push($(this).next().text().trim());
});

Looks like .map() is probably the more sophisticated way to go though.

0

精彩评论

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