首页 > 解决方案 > 如何使我的 HTML 命令框与 JavaScript 一起使用?

问题描述

我有一个 HTML 命令框,它应该执行命令,例如更改样式表和类似的东西。我以为我做了一些魔法,但它根本不起作用。这是其中包含 JS 和 CSS 的 HTML。随意提出建议,或者如果你认为你有一个想法。

function checkCommand() {
  var tempStyle = document.getElementById('temp-style')
  var commandInput = document.getElementById('text-box')

  if (commandInput.value == black) {
    tempStyle.setAttribute("href", "black.css")
  }

  if (commandInput.value == orange) {
    tempStyle.setAttribute("href", "orange.css")
  }

  if (commandInput.value == white) {
    tempStyle.setAttribute("href", "white.css")
  }

  if (commandInput.value == windows) {
    tempStyle.setAttribute("href", "windows.css")
  }
}
#text-box {
  font-size: 18px;
  width: 500px;
  height: 20px;
}

#submit-form {
  display: none;
}
<link rel="stylesheet" type="text/css" href="white.css" id="temp-style">
<form id="command-form">
  <input type="text" id="text-box" placeholder="Enter Command">
  <input type="submit" id="submit-form" onclick="checkCommand()">
</form>
<p><b>Black:</b> Background color changes to black and text color changes to white
  <br><b>Orange:</b> Background color changes to orange and text color changes to blue
  <br><b>White (Default):</b> Background color changes to white and text color changes to black
  <br>
  <br><b>Windows:</b> Background image changes to Windows XP Bliss and text color changes to black</p>


编辑

旁注:为什么当我只应用 HTML 标签时它看起来很棒,但是当 JS 标签在其中时,它试图将整个东西变成 JS?不太重要,但我有强迫症,所以它很难发挥作用。

标签: javascripthtml

解决方案


I needed to add an extra "=" sign to every if condition because I was referring to a string, and I needed to put the string in quotes. After I submitted the form, it refreshed the page, so no content was saved. The fix for that was simply adding "event.preventDefault();" to the end of the checkCommand(); function. Here is the final JavaScript product. Everything else worked great.

JavaScript

function checkCommand() {
    var tempStyle = document.getElementById('temp-style')
    var commandInput = document.getElementById('text-box')

    if ( commandInput.value === "black" ) {
        tempStyle.setAttribute("href", "black.css")
    }

    if ( commandInput.value === "orange" ) {
        tempStyle.setAttribute("href", "orange.css")
    }

    if ( commandInput.value === "white" ) {
        tempStyle.setAttribute("href", "white.css")
    }

    if ( commandInput.value === "windows" ) {
        tempStyle.setAttribute("href", "windows.css")
    }

    form.reset();

    event.preventDefault();
}

Edits

I also added "form.reset();" before "event.preventDefault();" so it clears the form as you press enter.


推荐阅读