简体   繁体   English

如何使用javascript动态添加html类

[英]How to add html class dynamically with javascript

I have a login page with the texbox to email and password and I use Bootstrap framework to css style.我有一个带有文本框到电子邮件和密码的登录页面,我使用 Bootstrap 框架来设置 css 样式。 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 eventhttps://getbootstrap.com/docs/4.4/components/forms/#server-side此事件的引导程序文档https://getbootstrap.com/docs/4.4/components/forms/#server-side

Into tag script进入标签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");
        }
      }

Into html body进入 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>

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 == "") {
    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");
  }

Note: The assumption is that you are calling this code inside your click handler (which you also have called verifyErrors()).注意:假设您在单击处理程序中调用此代码(您也调用了 verifyErrors())。 I assume you have retrieved the values of password and email in the method before the if statements我假设您已经在 if 语句之前的方法中检索了密码和电子邮件的值

Color is not changing because you have not remove the class previously used on that specific div.颜色没有改变,因为您没有删除先前在该特定 div 上使用的类。 Try removing the class then add new class to list.尝试删除类,然后将新类添加到列表中。

Try this instead:试试这个:

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");
    }
  }

The issue overall is your use of JS.总体而言,问题是您对 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).如何使用 classList.add(如有疑问,请阅读文档)。
  • 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)基本函数(如“Array.forEach”),无需复制验证函数(只需使用一个并为其提供要验证的元素列表)
  • 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.我强烈建议彻底阅读几十本“入门 JavaScript”书籍中的一本(不仅仅是略读,而是一些真正的研究),以及“JavaScript,好的部分”作为一种宝贵的资源,可以帮助您了解正确使用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.如果您尝试在测试或示例中按原样使用您的代码,您可能会得到一些非常严厉的回应。

<html>
    <head>
    <style>
    .form-control {
      width: 300px;
     }
    .is-invalid {
      border: 2px solid red;
    }
    </style>
    </head>
    <body>
       <script>
           // "elems" 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 => { 
              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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM