Home > Enterprise >  Style with CSS variables in $.each()
Style with CSS variables in $.each()

Time:10-20

I'm trying to add style to the link's "values" variables, but with no success. can anybody help me?

Example of the code I'm using:

$(document).ready(function(){
  $(".guide").append(function(){
    $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page1!A2:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI"
    
, function(result){
      $.each(result.values, function(i, field){
        $(".guide").append( '<div style="font-size: 12px;">'   field   '</div>'  '<div style="font-size: 14px;">'   field   '</div>'   '<div style="font-size: 18px;">'   field   '</div>');
      });
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

According to your data structure you MUST "loop" on result.values[0], and store your "style" in array then access corresponding index (i) for both value et style.

$(document).ready(function(){
  $(".guide").append(function(){
    $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page1!A2:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI"
    
, function(result){
      let style = ['12','14','18'];
      $.each(result.values[0], function(i, field){
        $(".guide").append( '<div style="font-size:' style[i] 'px;">'   field   '</div>');
      });
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But there is a more appropriate way to do this shared by Chris G using Array.map

https://jsfiddle.net/khrismuc/g16fxd79/

CodePudding user response:

Consider the following: https://jsfiddle.net/Twisty/08a2rps7/11/

HTML

<div class="guide"></div>

CSS

.sm {
  font-size: 12px;
}
.rg {
  font-size: 14px;
}
.lg {
  font-size: 18px;
}

JavaScript

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page1!A2:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    var classes = [
      "sm",
      "rg",
      "lg"
    ];
    $.each(result.values[0], function(i, field) {
      $(".guide").append('<span hljs-string">'">'   field   '</span>');
    });
  });
});

You can choose to use DIV versus SPAN yet DIV naturally Blocks where as SPAN is Inline. Your result.values is an Array or Arrays, therefore, field is an array. You must index it properly to get each part.

  • Related