在 if 语句中声明的变量会导致“未定义的变量" [英] Variables declared inside an if statement results in "undefined variable"

查看:67
本文介绍了在 if 语句中声明的变量会导致“未定义的变量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在 if 语句中定义变量可以在 Sass 中工作,但不幸的是我收到错误消息,指出变量未定义.这是我尝试过的:

I was hoping that defining variables in an if statement would work in Sass but unfortunately I get errors saying that the variable isn't defined. Here is what I tried:

@for !i from 1 through 9
    !foo = #000
    @if !i == 1
        !bg_color = #009832
    @if !i == 2
        !bg_color = #195889
    ...

    #bar#{!i} 
        color: #{!foo}
        background-color: #{!bg_color}

使用此代码,我会收到以下错误:

With this code, I would get the following error:

未定义变量:!bg_color".

Undefined variable: "!bg_color".

推荐答案

Sass 变量仅对声明它们的缩进级别以及嵌套在其下的那些变量可见.所以你只需要在 for 循环之外声明 !bg_color :

Sass variables are only visible to the level of indentation at which they are declared and those nested underneath it. So you only need to declare !bg_color outside of your for loop:

!bg_color = #FFF
@for !i from 1 through 9
    !foo = #000
    @if !i == 1
        !bg_color = #009832
    @if !i == 2
        !bg_color = #195889

    #bar#{!i} 
        color: #{!foo}
        background-color: #{!bg_color}

您将获得以下 css:

And you'll get the following css:

#bar1 {
  color: black;
  background-color: #009832; }

#bar2 {
  color: black;
  background-color: #195889; }

#bar3 {
  color: black;
  background-color: #195889; }

#bar4 {
  color: black;
  background-color: #195889; }

#bar5 {
  color: black;
  background-color: #195889; }

#bar6 {
  color: black;
  background-color: #195889; }

#bar7 {
  color: black;
  background-color: #195889; }

#bar8 {
  color: black;
  background-color: #195889; }

#bar9 {
  color: black;
  background-color: #195889; }

这篇关于在 if 语句中声明的变量会导致“未定义的变量"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆