![](/img/trans.png)
[英]How to put values from an array of objects into a new array in JavaScript
[英]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.