如何使用JavaScript动态添加HTML类?

huangapple go评论81阅读模式
英文:

How to add html class dynamically with javascript

问题

我有一个登录页面,其中包含用于输入电子邮件和密码的文本框,我使用Bootstrap框架来进行CSS样式设置。我想要在输入文本框为空时将边框颜色从灰色更改为红色,然后用户单击登录按钮。我编写了代码,但当我单击登录按钮时,颜色不会更改。

Bootstrap文档中关于此事件的信息:https://getbootstrap.com/docs/4.4/components/forms/#server-side

<script>标签内部

if (password == "") {
    function verifyError() {
        var element = document.getElementById("password");
        element.classList.add("form-control is-invalid");
    }
}

if (email == "") {
    function verifyError() {
        var element = document.getElementById("email");
        element.classList.add("form-control is-invalid");
    }
}

在HTML主体部分

<div class="col-md-4 mb-1">
    <input id="email" type="text" class="form-control" placeholder="Email">
</div>
<br>
<div class="col-md-4">
    <input id="password" type="text" class="form-control" placeholder="Password">
</div>
<br>
<button id="login" type="button" value="login" class="btn purple" onclick="verifyError()">Login</button>
英文:

I have a login page with the texbox to email and password and I use Bootstrap framework to css style. I would change the border color from grey to red of input textbox interesting when it is empty then the user click the button to login. I wrote the code but when I click the button to login the color don't change.

Bootstrap documentation of this event https://getbootstrap.com/docs/4.4/components/forms/#server-side

Into tag script

     if(password == &quot;&quot;) {
        function verifyError() {
          var element = document.getElementById(&quot;password&quot;);
          element.classList.add(&quot;form-control is-invalid&quot;);
        }
      }

      if (email == &quot;&quot;) {
        function verifyError() {
          var element = document.getElementById(&quot;email&quot;);
          element.classList.add(&quot;form-control is-invalid&quot;);
        }
      }

Into html body

        &lt;div class=&quot;col-md-4 mb-1&quot;&gt;
          &lt;input id=&quot;email&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Email&quot;&gt;
        &lt;/div&gt;
        &lt;br&gt;
        &lt;div class=&quot;col-md-4&quot;&gt;
          &lt;input id=&quot;password&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Password&quot;&gt;
        &lt;/div&gt;
        &lt;br&gt;
        &lt;button id=&quot;login&quot; type=&quot;button&quot; value=&quot;login&quot; class=&quot;btn purple&quot; onclick=&quot;verifyError()&quot;&gt;Login&lt;/button&gt;

答案1

得分: 3

这个不起作用的原因是,当密码/电子邮件为空时,你只是在定义一个函数。要执行其中的操作,你必须调用你定义的函数。然而,我认为你实际上并不需要这些函数。

尝试这样做:

if(password == "") {
    var passElem = document.getElementById("password");
    passElem.classList.add("form-control is-invalid");
}

if (email == "") {
    var emailElem = document.getElementById("email");
    emailElem.classList.add("form-control is-invalid");
}

注意:假设你是在点击处理程序内调用此代码(你还将其称为verifyErrors())。我假设在if语句之前的方法中已经获取了密码和电子邮件的值。

英文:

The reason for it not doing anything is that you are just defining a function when the password/email are empty. You have to call functions that you define in order for them to execute the operations within them. However, I don't think you actually need the functions.

Try this:

 if(password == &quot;&quot;) {
    var passElem = document.getElementById(&quot;password&quot;);
    passElem.classList.add(&quot;form-control is-invalid&quot;);
  }

  if (email == &quot;&quot;) {
    var emailElem = document.getElementById(&quot;email&quot;);
    emailElem.classList.add(&quot;form-control is-invalid&quot;);
  }

Note: The assumption is that you are calling this code inside your click handler (which you also have called verifyErrors()). I assume you have retrieved the values of password and email in the method before the if statements

答案2

得分: 1

颜色没有改变是因为您没有先删除特定 div 上先前使用的类。尝试删除该类,然后添加新的类到列表。

请尝试以下代码:

if(password == "") {
    function verifyError() {
        var element = document.getElementById("password");
        element.classList.remove("form-control");
        element.classList.add("form-control is-invalid");
    }
}

if (email == "") {
    function verifyError() {
        var element = document.getElementById("email");
        element.classList.remove("form-control");
        element.classList.add("form-control is-invalid");
    }
}
英文:

Color is not changing because you have not remove the class previously used on that specific div. Try removing the class then add new class to list.

Try this instead:

if(password == &quot;&quot;) {
    function verifyError() {
      var element = document.getElementById(&quot;password&quot;);
      element.classList.remove(&quot;form-control&quot;)
      element.classList.add(&quot;form-control is-invalid&quot;);
    }
  }

  if (email == &quot;&quot;) {
    function verifyError() {
      var element = document.getElementById(&quot;email&quot;);
      element.classList.remove(&quot;form-control&quot;)
      element.classList.add(&quot;form-control is-invalid&quot;);
    }
  }

答案3

得分: 1

问题总体来说是你对JavaScript的使用有问题。在你的方法中存在一些基本问题(对于这个问题真的没有一个快速的答案)。下面的代码将是一个很好的示例,可以帮助你继续前进,但为了彻底解决问题,你确实需要仔细审查:

  • 作用域(变量何时何地需要声明)
  • 如何使用classList.add(如果有疑问,请阅读文档)。
  • 基本函数(比如"Array.forEach"),没有必要复制verify函数(只需使用一个并将要验证的元素列表传递给它)
  • 如何检查“falsy”值(== "")存在问题
  • 以此类推。

我强烈建议你彻底阅读几本“Beginning JavaScript”书籍(不仅仅是浏览,而是认真学习),并将“JavaScript, the Good Parts”视为一个有价值的资源,帮助你正确使用JavaScript。请注意,如果你尝试在测试中使用你的代码或作为示例,你可能会得到一些相当严厉的反馈。

<html>
<head>
<style>
.form-control {
  width: 300px;
 }
.is-invalid {
  border: 2px solid red;
}
</style>
</head>
<body>
   <script>
       // "elems"应该是一个要验证的字段名称数组,这样你可以一次性验证它们。
       function verifyError( elems ) {
         elems.forEach ( x => { 
          var element = document.getElementById(x);
          element.classList = !element.value ? [ 'form-control is-invalid' ] : [ 'form-control' ];
         });
        }
   </script>

<div class="col-md-4 mb-1">
  <input id="email" type="text" class="form-control" placeholder="Email">
</div>
<br>
<div class="col-md-4">
  <input id="password" type="text" class="form-control" placeholder="Password">
</div>
<br>
<button id="login" type="button" value="login" class="btn purple" onclick="verifyError( ['password', 'email'] )">Login</button>


</body>
</html>
英文:

The issue overall is your use of JS. There's quite a few basic problems in your approach (there really is no one quick answer to the issue). The below code will be a good example of how to get you moving forward, but to be thorough, you really need to review :

  • Scope (when and where variables need to be declared)
  • How to use classList.add (when in doubt, read the docs).
  • Basic functions (like "Array.forEach), there's no need to duplicate the verify function (just use one and feed it a list of
    elements you want to validate)
  • How to check for a "falsy" value (== "") is problematic
  • And so on.

I'd strongly recommend a thorough read of one of the dozens of "Beginning JavaScript" books (not just a skim but some real study), and "JavaScript, the Good Parts" as a valuable resource to getting your head around the path to correct use of Javascript. Be forewarned; if you were trying to use your code as-is in a test or as a sample, you might get some pretty harsh response.

&lt;html&gt;
    &lt;head&gt;
    &lt;style&gt;
    .form-control {
      width: 300px;
     }
    .is-invalid {
      border: 2px solid red;
    }
    &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
       &lt;script&gt;
           // &quot;elems&quot; should be an array of the field names you want to validate, so you can do all of them at once.
           function verifyError( elems ) {
             elems.forEach ( x =&gt; { 
              var element = document.getElementById(x);
              element.classList = !element.value ? [ &#39;form-control is-invalid&#39; ] : [ &#39;form-control&#39; ];
             });
            }
       &lt;/script&gt;
    
    &lt;div class=&quot;col-md-4 mb-1&quot;&gt;
      &lt;input id=&quot;email&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Email&quot;&gt;
    &lt;/div&gt;
    &lt;br&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
      &lt;input id=&quot;password&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Password&quot;&gt;
    &lt;/div&gt;
    &lt;br&gt;
    &lt;button id=&quot;login&quot; type=&quot;button&quot; value=&quot;login&quot; class=&quot;btn purple&quot; onclick=&quot;verifyError( [&#39;password&#39;, &#39;email&#39;] )&quot;&gt;Login&lt;/button&gt;
    
    
    &lt;/body&gt;
    &lt;/html&gt;

huangapple
  • 本文由 发表于 2020年1月3日 20:41:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定