简体   繁体   中英

Javascript: Put array of objects values to divs

I want to store properties (text length and style) of several divs into an array. Then I want to put the values of the style keys in other divs according to div text length.

$("#blocks .block span").each(function() {
     blockspansizes.push({length: $(this).text().length, style:$(this).attr("style")});              
});//text lengths are all different.


$(".newblocks span").each(function() {
         textlength = (this).text().length
 //if textlength matches one length value from array, get its corresponding style from the same object.
    });

You cant push to array like that and then compare the values. You can do it with key/value pairs:

$("#blocks .block span").each(function() {
   blockspansizes[$(this).text().length]=$(this).attr("style");              
 });//text lengths are all different.


$(".newblocks span").each(function() {
     textlength = (this).text().length;
      //if textlength matches one length value from array, get its corresponding style from  the      same object.
     if(blockspansizes.indexOf(textlength) > -1){
        //do something with blockspansizes[textlength]
     }

});

Thank you for the kind help, vodich. Here's how I managed to make it work:

    blockspansizes = new Array();
$("#blocks .block span").each(function() {
    blockspansizes.push({length: $(this).text().length, style:$(this).attr("style")});               
});

$(".newblock span").each(function() {
    textlength = $(this).text().length;
    result = $.grep(blockspansizes, function(e){ return e.length == textlength; });
    $(this).attr("style", result[0].style);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM