簡體   English   中英

Javascript:將對象值數組放入div

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

我想將幾個div的屬性(文本長度和樣式)存儲到數組中。 然后,我想根據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.
    });

您不能像這樣推送到數組,然后比較值。 您可以使用鍵/值對來做到這一點:

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

});

謝謝您的幫助。 這是我設法使其工作的方法:

    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