简体   繁体   English

Javascript:将对象值数组放入div

[英]Javascript: Put array of objects values to divs

I want to store properties (text length and style) of several divs into an array. 我想将几个div的属性(文本长度和样式)存储到数组中。 Then I want to put the values of the style keys in other divs according to div text length. 然后,我想根据div文本长度将样式键的值放在其他div中。

$("#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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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