【问题标题】:else/if statement only runs onceelse/if 语句只运行一次
【发布时间】:2022-01-12 14:32:28
【问题描述】:

目前在我的代码中,如果用户输入的颜色与数组中的任何颜色相匹配,它将将该颜色类添加到主 div。

问题是我的 else if 语句只运行一次。如果您重新输入相同的颜色,它不会在运行不同的颜色后再次添加该类(例如黑色 > 红色 > 黑色)。

还有其他方法可以解决这个问题吗?

'use strict';

let inputElement = document.getElementById('inpp');
const btn = document.getElementById('btn');
let outputValue = document.getElementById('output');
const bodyEl = document.getElementById('thisBody');

btn.addEventListener('click', (e) => {
    // Prevent form from reloading page
    e.preventDefault();
  
  let inputValue = inputElement.value;
  
  let favColors = [
    'black',
    'red',
    'blue',
    'green',
    'yellow',
    'pink',
    'orange',
    'brown',
    'white',
    'purple'
  ];
  
  // If user input match
  if (favColors.includes(inputValue)) {
    outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
  } else if (inputValue === '') {
    outputValue.innerHTML = `Please enter a color..`;
  } else {
    outputValue.innerHTML = `Interesting, ${inputValue} is new to me!`;
  }

  // Add color classes on match
  if (favColors[0] === inputValue) {
    bodyEl.classList.add('black');
  } else if (favColors[1] === inputValue) {
    bodyEl.classList.add('red');
  } else if (favColors[2] === inputValue) {
    bodyEl.classList.add('blue');
  } else if (favColors[3] === inputValue) {
    bodyEl.classList.add('green');
  } else if (favColors[4] === inputValue) {
    bodyEl.classList.add('yellow');
  } else if (favColors[5] === inputValue) {
    bodyEl.classList.add('pink');
  } else if (favColors[6] === inputValue) {
    bodyEl.classList.add('orange');
  } else if (favColors[7] === inputValue) {
    bodyEl.classList.add('brown');
  } else if (favColors[8] === inputValue) {
    bodyEl.classList.add('white');
  } else if (favColors[9] === inputValue) {
    bodyEl.classList.add('purple');
  } 
  
  // Clear input value
  inputElement.value = '';
});
/* Color classes */
.black {
  background-color: black !important;
}

.red {
  background-color: red !important;
}

.blue {
  background-color: blue !important;
}

.green {
  background-color: green !important;
}

.yellow {
  background-color: yellow !important;
}

.pink {
  background-color: pink !important;
}

.orange {
  background-color: orange !important;
}

.brown {
  background-color: brown !important;
}

.white {
  background-color: white !important;
}

.purple {
  background-color: purple !important;
}
<div id="thisBody">
  <div class="container">
    <div class="content">
      <div>
        <h1 id="output">What's your favorite color?</h1>
        <form id="formy">
          <input id="inpp" type="text" placeholder="What's your favorite color?">
          <button type="submit" id="btn">Submit</button>
        </form>
      </div>
    </div>
  </div>
 </div>

【问题讨论】:

  • (1) 您添加与颜色相关的类,但从不删除它们;(2) 当您在彼此之上添加类时,只会考虑最后一个(例如 class="pink purple"将忽略“粉红色”)。

标签: javascript html css


【解决方案1】:

首先,您的代码可以很容易地缩减为:

  // Add color classes on match
  if (favColors[0] === inputValue) {
    bodyEl.classList.add('black');
  } else if (favColors[1] === inputValue) {
    bodyEl.classList.add('red');
  } else if (favColors[2] === inputValue) {
    bodyEl.classList.add('blue');
  } else if (favColors[3] === inputValue) {
    bodyEl.classList.add('green');
  } else if (favColors[4] === inputValue) {
    bodyEl.classList.add('yellow');
  } else if (favColors[5] === inputValue) {
    bodyEl.classList.add('pink');
  } else if (favColors[6] === inputValue) {
    bodyEl.classList.add('orange');
  } else if (favColors[7] === inputValue) {
    bodyEl.classList.add('brown');
  } else if (favColors[8] === inputValue) {
    bodyEl.classList.add('white');
  } else if (favColors[9] === inputValue) {
    bodyEl.classList.add('purple');
  } 

收件人:

  if(favColors.includes(inputValue)) bodyEl.classList.add(inputValue);

那么您面临的问题是您向classList 添加了两次。要解决此问题,只需在添加之前删除所有喜欢的颜色:

  if(favColors.includes(inputValue)) {
    bodyEl.classList.remove(...favColors);
    bodyEl.classList.add(inputValue);
  }

编辑:

如果您真的想将类堆叠在一起(我认为这不是您的用例),那么您可以这样做:

  if(favColors.includes(inputValue)) {
    bodyEl.classList.remove(inputValue);
    bodyEl.classList.add(inputValue);
  }

【讨论】:

  • if(favColors.includes(inputValue)) { bodyEl.classList.remove(inputValue); bodyEl.classList.add(inputValue); } 没有任何意义
  • @mplungjan 是的:如果之前在列表中,则从列表中删除,然后将其添加回顶部
  • 所以它们会被堆叠起来......听起来很奇怪
  • 这是一个奇怪的逻辑但是如果你有 ["red", "blue", "green"],并且你想再次添加红色,它将首先删除:-> ["blue", "green"],然后在顶部添加红色:-> ["blue", "green", "red"],这里红色优先。如果您没有进行删除,那么您将拥有 ["red", "blue", "green", "red"] 并且第一个红色将是使用的但不会优先
【解决方案2】:

您需要删除旧颜色。您也可以使用数组进行检查。

'use strict';

let inputElement = document.getElementById('inpp');
const btn = document.getElementById('btn');
let outputValue = document.getElementById('output');
const bodyEl = document.getElementById('thisBody');
let lastColor;

btn.addEventListener('click', (e) => {
    // Prevent form from reloading page
    e.preventDefault();
  
  let inputValue = inputElement.value;
  
  let favColors = ['black', 'red', 'blue', 'green', 'yellow', 'pink', 'orange', 'brown', 'white', 'purple'];
  
  // If user input match
  if (favColors.includes(inputValue)) {
    outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
  } else if (inputValue === '') {
    outputValue.innerHTML = `Please enter a color..`;
  } else {
    outputValue.innerHTML = `Interesting, ${inputValue} is new to me!`;
  }

  // Add color classes on match
  if (favColors.includes(inputValue)) {
      if (lastColor) bodyEl.classList.remove(lastColor);
      bodyEl.classList.add(inputValue);
      lastColor = inputValue;
  }
  
  // Clear input value
  inputElement.value = '';
});
.black { background-color: black !important; }
.red { background-color: red !important; }
.blue { background-color: blue !important; }
.green { background-color: green !important; }
.yellow { background-color: yellow !important; }
.pink { background-color: pink !important; }
.orange { background-color: orange !important; }
.brown { background-color: brown !important; }
.white { background-color: white !important; }
.purple { background-color: purple !important; }
<div id="thisBody">
  <div class="container">
    <div class="content">
      <div>
        <h1 id="output">What's your favorite color?</h1>
        <form id="formy">
          <input id="inpp" type="text" placeholder="What's your favorite color?">
          <button type="submit" id="btn">Submit</button>
        </form>
      </div>
    </div>
  </div>
 </div>

【讨论】:

  • 您不需要跟踪,即使当前值从类列表中丢失,您也可以随时删除它
【解决方案3】:

您的ifs 确实执行了多次。但是,您只添加新的颜色类。你永远不会清除旧的。要清除它们,请在您的 ifs 之前添加此代码

bodyEl.className = "";

演示:

'use strict';

let inputElement = document.getElementById('inpp');
const btn = document.getElementById('btn');
let outputValue = document.getElementById('output');
const bodyEl = document.getElementById('thisBody');

btn.addEventListener('click', (e) => {
    // Prevent form from reloading page
    e.preventDefault();
  
  let inputValue = inputElement.value;
  
  let favColors = [
    'black',
    'red',
    'blue',
    'green',
    'yellow',
    'pink',
    'orange',
    'brown',
    'white',
    'purple'
  ];
  
  // If user input match
  if (favColors.includes(inputValue)) {
    outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
  } else if (inputValue === '') {
    outputValue.innerHTML = `Please enter a color..`;
  } else {
    outputValue.innerHTML = `Interesting, ${inputValue} is new to me!`;
  }
  
  // remove previous color
  bodyEl.className = "";

  // Add color classes on match
  if (favColors[0] === inputValue) {
    bodyEl.classList.add('black');
  } else if (favColors[1] === inputValue) {
    bodyEl.classList.add('red');
  } else if (favColors[2] === inputValue) {
    bodyEl.classList.add('blue');
  } else if (favColors[3] === inputValue) {
    bodyEl.classList.add('green');
  } else if (favColors[4] === inputValue) {
    bodyEl.classList.add('yellow');
  } else if (favColors[5] === inputValue) {
    bodyEl.classList.add('pink');
  } else if (favColors[6] === inputValue) {
    bodyEl.classList.add('orange');
  } else if (favColors[7] === inputValue) {
    bodyEl.classList.add('brown');
  } else if (favColors[8] === inputValue) {
    bodyEl.classList.add('white');
  } else if (favColors[9] === inputValue) {
    bodyEl.classList.add('purple');
  } 
  
  // Clear input value
  inputElement.value = '';
});
/* Color classes */
.black {
  background-color: black !important;
}

.red {
  background-color: red !important;
}

.blue {
  background-color: blue !important;
}

.green {
  background-color: green !important;
}

.yellow {
  background-color: yellow !important;
}

.pink {
  background-color: pink !important;
}

.orange {
  background-color: orange !important;
}

.brown {
  background-color: brown !important;
}

.white {
  background-color: white !important;
}

.purple {
  background-color: purple !important;
}
<div id="thisBody">
  <div class="container">
    <div class="content">
      <div>
        <h1 id="output">What's your favorite color?</h1>
        <form id="formy">
          <input id="inpp" type="text" placeholder="What's your favorite color?">
          <button type="submit" id="btn">Submit</button>
        </form>
      </div>
    </div>
  </div>
 </div>

但是,对于更有效的方法,请参阅 @mplungjanAnswer

【讨论】:

    【解决方案4】:

    找到时设置颜色

    您可以保存旧颜色并在设置前将其删除

    如果bgcolor是黑色,我也建议你将颜色改为白色

    let saveColor = "";
     ...
    
    
    if (favColors.includes(inputValue)) {
      outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
      if (saveColor) bodyEl.classList.remove(saveColor);
      bodyEl.classList.add(inputValue);
      saveColor = inputValue;
      bodyEl.style.color = inputValue === "black" ? "white" : "black"
    }
    

    'use strict';
    
    const favColors = ['black', 'red', 'blue', 'green', 'yellow', 'pink', 'orange', 'brown', 'white', 'purple'];
    
    let saveColor = "";
    let inputElement = document.getElementById('inpp');
    const btn = document.getElementById('btn');
    let outputValue = document.getElementById('output');
    const bodyEl = document.getElementById('thisBody');
    
    btn.addEventListener('click', (e) => {
      // Prevent form from reloading page
      e.preventDefault();
    
      let inputValue = inputElement.value;
    
      // If user input match
      if (favColors.includes(inputValue)) {
        outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
        if (saveColor) bodyEl.classList.remove(saveColor);
        bodyEl.classList.add(inputValue);
        saveColor = inputValue;
        bodyEl.style.color = inputValue === "black" ? "white" : "black"
      } else if (inputValue === '') {
        outputValue.innerHTML = `Please enter a color..`;
      } else {
        outputValue.innerHTML = `Interesting, ${inputValue} is new to me!`;
      }
    
      // Clear input value
      inputElement.value = '';
    });
    /* Color classes */
    
    .black {
      background-color: black !important;
    }
    
    .red {
      background-color: red !important;
    }
    
    .blue {
      background-color: blue !important;
    }
    
    .green {
      background-color: green !important;
    }
    
    .yellow {
      background-color: yellow !important;
    }
    
    .pink {
      background-color: pink !important;
    }
    
    .orange {
      background-color: orange !important;
    }
    
    .brown {
      background-color: brown !important;
    }
    
    .white {
      background-color: white !important;
    }
    
    .purple {
      background-color: purple !important;
    }
    <div id="thisBody">
      <div class="container">
        <div class="content">
          <div>
            <h1 id="output">What's your favorite color?</h1>
            <form id="formy">
              <input id="inpp" type="text" placeholder="What's your favorite color?">
              <button type="submit" id="btn">Submit</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    【讨论】:

    • 你在这里清除了所有以前的课程。也许他们还有其他想要保留的课程
    • @AlexandreSenges 不管怎样,我为你添加了一个 saveColor :)
    【解决方案5】:

    您添加与颜色相关的类,但从不删除它们,并且当您在彼此之上添加类时,只会考虑最后一个(例如 class="pink Purple" 将忽略“pink”)。

    'use strict';
    
    let inputElement = document.getElementById('inpp');
    const btn = document.getElementById('btn');
    let outputValue = document.getElementById('output');
    const bodyEl = document.getElementById('thisBody');
    
    btn.addEventListener('click', (e) => {
      // Prevent form from reloading page
      e.preventDefault();
    
      let inputValue = inputElement.value.toLowerCase(); // so "Black", "black" and "BLACK" will all work
    
      let favColors = [
        'black',
        'red',
        'blue',
        'green',
        'yellow',
        'pink',
        'orange',
        'brown',
        'white',
        'purple'
      ];
    
      // If user input match
      if (favColors.includes(inputValue)) {
        outputValue.innerHTML = `Awesome, ${inputValue} is so neat!`;
    
        // Add color classes on match (no need to have a separate `if`)
        // remove any previously set color: the reason for looping through `favColors`
        // is to preserve any class not related to color that you might have on the element
        favColors.forEach(color => bodyEl.classList.remove(color));
        // add the new color
        bodyEl.classList.add(inputValue);
      } else if (inputValue === '') {
        outputValue.innerHTML = `Please enter a color..`;
      } else {
        outputValue.innerHTML = `Interesting, ${inputValue} is new to me!`;
      }
    
      // Clear input value
      inputElement.value = '';
    });
    /* Color classes */
    
    .black {
      background-color: black !important;
      color: white;
    }
    
    .red {
      background-color: red !important;
    }
    
    .blue {
      background-color: blue !important;
    }
    
    .green {
      background-color: green !important;
    }
    
    .yellow {
      background-color: yellow !important;
    }
    
    .pink {
      background-color: pink !important;
    }
    
    .orange {
      background-color: orange !important;
    }
    
    .brown {
      background-color: brown !important;
    }
    
    .white {
      background-color: white !important;
    }
    
    .purple {
      background-color: purple !important;
    }
    <div id="thisBody">
      <div class="container">
        <div class="content">
          <div>
            <h1 id="output">What's your favorite color?</h1>
            <form id="formy">
              <input id="inpp" type="text" placeholder="What's your favorite color?">
              <button type="submit" id="btn">Submit</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    附:我还对您的代码进行了一些优化并插入了 cmets 以供进一步解释

    【讨论】:

      【解决方案6】:

      Element.classList 是一个 DOMTokenList 接口表示一组以空格分隔的标记。

      集合看起来像数组,但对于一个集合,所有的值都是唯一的,你不能再次向其中添加相同的值。

      另外,向一个元素多次添加同一个类也不会产生任何影响。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-16
        • 2015-08-23
        • 1970-01-01
        • 2017-09-11
        • 2023-01-12
        • 2019-05-09
        相关资源
        最近更新 更多