javascript - 如何使我的 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?不太重要,但我有强迫症,所以它很难发挥作用。
解决方案
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.
推荐阅读
- ios - Swift:UICollectionView 中的单选按钮
- c++ - 了解 std::optional 在不同平台上的性能差异
- angular - Angular 7.2.15,由于后退导航,在导航(popstate)之后访问 RestoredState 数据
- javascript - webrtc udp协议规范格式webrtc udp转c#udp服务器解包收到的udp数据
- django - 如何在 Django 中测试 PasswordChangeView?
- c++ - cocos2d-x中精灵为什么会颤抖
- python-3.x - 如何使用父类强制子类为属性设置值?
- laravel - 如何在 if 语句中使用 laravel db query ->update() 方法
- firefox - 访问特定域时如何聚焦 Firefox 窗口
- keytool - 出现错误 java.security.KeyStoreException: PKCS11 not found while using softhsm as hsm