只运行两个几乎相同的JavaScript函数中的一个

时间:2017-05-29 12:42:45

标签: javascript html

我可能在这里非常愚蠢...

我有两个实际上相同的JavaScript函数,除了每个函数引用不同的元素。

想法是在文档加载时显示和隐藏Toast / notification。

对于一个元素(errorexplanationcontainer),它可以工作......对于另一个元素(警报),它不会...

errorexplanationcontainer(WORKS)的代码

<div id="errorexplanationcontainer" class=""></div>

      <script type="text/javascript">
        window.onload = function() {
          var z = document.getElementById("errorexplanationcontainer")
          z.className = "show";
          setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
        }
      </script>

^^这是从Google Chrome中的检查窗口复制并粘贴的。如您所见,脚本成功运行。我们知道这一点,因为源文档中不存在class=""并且已由脚本添加(在显示class="show" 3秒后)。

警报代码(不工作)

<p id="alert">Invalid Email or password.</p>
      <script type="text/javascript">
        window.onload = function() {
          var y = document.getElementById("alert")
          y.className = "show";
          setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
        }
      </script>

^^这里没有class=""!该脚本没有工作......

完整的HTML DOC

<html class="mdl-js"><head>
  <title>Dennis' Coffee Hut | CuppaDesk</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/png" href="/assets/favicon-16x16-347e46971826b54de74f354ae410242483f471bb3051a5f948d83af70770dadc.png" sizes="16x16">
  <link rel="icon" type="image/png" href="/assets/favicon-32x32-ac516884b2aa2ea870ddfbd0ae383c0dd66ec1a640181174ac7adaba8e7ccd7d.png" sizes="32x32">
  <link rel="apple-touch-icon" type="image/x-icon" href="/assets/apple-touch-icon-af3f73bee131a689a15fede0d2d6f7cf9698786524670279ac74cd128ec5dc40.png" sizes="180x180">
  <link rel="mask-icon" type="image/x-icon" href="/assets/safari-pinned-tab-4f97411db829aebf4a4796a8f216e788ba4eeddf4d062a0a1efe473ee10fce3b.svg" color="#99cc33">
  <link rel="icon" type="image/png" href="/assets/android-chrome-192x192-cb0ced957daf2743c293b898f5e595fcf07fc0842b9d0aeef37c08b8c5f74d42.png" sizes="192x192">
  <link rel="manifest" href="/manifest.json">
  <meta name="apple-mobile-web-app-title" content="CuppaDesk">
  <meta name="application-name" content="CuppaDesk">
  <meta name="msapplication-TileColor" content="#99cc33">
  <meta name="msapplication-TileImage" content="/assets/mstile-144x144-5de954b6d137b31283af01b9a7645c90440392de2b44ec88949fdba65cca75e7.png">
  <meta name="theme-color" content="#99cc33">

  <meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
  <link rel="stylesheet" media="all" href="/assets/main.self-b06bcba5344c9fc9a5c6491a38f0780f4594d723339bc0543a25138d83fe3de3.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/places.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-f0d704deea029cf000697e2c0181ec173a1b474645466ed843eb5ee7bb215794.css?body=1" data-turbolinks-track="reload">
  <script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/places.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-eba3cb53a585a0960ade5a8cb94253892706bb20e3f12097a13463b1f12a4528.js?body=1" data-turbolinks-track="reload"></script>

  <!-- BEGIN MATERIAL DESIGN LITE -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <!-- <link rel="stylesheet" href="/material.min.css"> -->
  <script defer="" src="https://code.getmdl.io/1.3.0/material.min.js"></script>
  <!-- END MATERIAL DESIGN LITE -->

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  </head>

  <body>
      <p id="alert">Invalid Email or password.</p>
      <script type="text/javascript">
        window.onload = function() {
          var y = document.getElementById("alert")
          y.className = "show";
          setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
        }
      </script>

    <div id="login-container">
  <div id="cuppadesk-logo-large"></div>
  <div id="card-white">

    <h1>Log in</h1>

    <div class="dropdown-dots">
      <button onclick="dotsDropdown()" class="dropbtn-dots"></button>
      <div id="dotsDropdown" class="dropdown-content">

  <a href="/users/sign_up">
    <div class="dropdown-content-item">Sign up</div>
</a>
  <a href="/users/password/new">
    <div class="dropdown-content-item">Forgot password</div>
</a>
  <a href="/users/confirmation/new">
    <div class="dropdown-content-item">Didn't recieve email confirmation</div>
</a>
  <a href="/users/unlock/new">
    <div class="dropdown-content-item">Didn't receive unlock instructions</div>
</a>
    <a href="/users/auth/facebook">
      <div class="dropdown-content-item">Log in with
        Facebook
      </div>
</a>
      </div>
    </div>

    <script>
      /* When the user clicks on the button,
      toggle between hiding and showing the dropdown content */
      function dotsDropdown() {
          document.getElementById("dotsDropdown").classList.toggle("show-dots");
      }

      // Close the dropdown menu if the user clicks outside of it
      window.onclick = function(event) {
        if (!event.target.matches('.dropbtn-dots')) {

          var dropdowns = document.getElementsByClassName("dropdown-content");
          var i;
          for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
              if (openDropdown.classList.contains('show-dots')) {
                openDropdown.classList.remove('show-dots');
              }
            }
          }
        }
    </script>

    <form class="new_user" id="new_user" action="/users/sign_in" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
      <div id="errorexplanationcontainer" class=""></div>

      <script type="text/javascript">
        window.onload = function() {
          var z = document.getElementById("errorexplanationcontainer")
          z.className = "show";
          setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
        }
      </script>

        <div class="field-white">
          <input autofocus="autofocus" placeholder="Email" type="email" value="" name="user[email]" id="user_email">
        </div>

        <div class="field-white">
          <input autocomplete="off" placeholder="Password" type="password" name="user[password]" id="user_password">
        </div>

          <div class="checkbox">
            <input name="user[remember_me]" type="hidden" value="0"><input class="css-checkbox" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me">
            <label class="css-label clr" for="user_remember_me">Remember me</label>
          </div>

        <script>
          // generic tools to help with the custom checkbox
          function UTIL() { }
          UTIL.prototype.bind_onclick = function(o, f) { // chain object onclick event to preserve prior statements (like jquery bind)
            var prev = o.onclick;
            if (typeof o.onclick != 'function') o.onclick = f;
            else o.onclick = function() { if (prev) { prev(); } f(); };
          };
          UTIL.prototype.bind_onload = function(f) { // chain window onload event to preserve prior statements (like jquery bind)
            var prev = window.onload;
            if (typeof window.onload != 'function') window.onload = f;
            else window.onload = function() { if (prev) { prev(); } f(); };
          };
          // generic css class style match functions similar to jquery
          UTIL.prototype.trim = function(h) {
            return h.replace(/^\s+|\s+$/g,'');
          };
          UTIL.prototype.sregex = function(n) {
            return new RegExp('(?:^|\\s+)' + n + '(?:\\s+|$)');
          };
          UTIL.prototype.hasClass = function(o, n) {
            var r = this.sregex(n);
            return r.test(o.className);
          };
          UTIL.prototype.addClass = function(o, n) {
            if (!this.hasClass(o, n))
                o.className = this.trim(o.className + ' ' + n);
          };
          UTIL.prototype.removeClass = function(o, n) {
            var r = this.sregex(n);
            o.className = o.className.replace(r, '');
            o.className = this.trim(o.className);
          };
          var U = new UTIL();

          function getElementsByClassSpecial(node, classname) {
              var a = [];
              var re = new RegExp('(^| )'+classname+'( |$)');
              var els = node.getElementsByTagName("*");
              for(var i=0,j=els.length; i<j; i++)
                  if(re.test(els[i].className))a.push(els[i]);
              return a;
          }


          // specific to customized checkbox

          function chk_labels(obj, init) {
            var objs = document.getElementsByTagName('LABEL');
            for (var i = 0; i < objs.length; i++) {
                if (objs[i].htmlFor == obj.id) {
                    if (!init) { // cycle through each label belonging to checkbox
                        if (!U.hasClass(objs[i], 'chk')) { // adjust class of label to checked style, set checked

                            if (obj.type.toLowerCase() == 'radio') {
                                var radGroup = objs[i].className;
                                var res = radGroup.split(" ");
                                var newRes = res[0] + " " + res[1];
                                var relLabels = getElementsByClassSpecial(document.body,newRes);
                                for (var r = 0; r < relLabels.length; r++) {
                                    U.removeClass(relLabels[r], 'chk');
                                    U.addClass(relLabels[r], 'clr');
                                }

                                U.removeClass(objs[i], 'clr');
                                U.addClass(objs[i], 'chk');
                                obj.checked = true;

                            }
                            else {
                                U.removeClass(objs[i], 'clr');
                                U.addClass(objs[i], 'chk');
                                obj.checked = true;
                            }
                        } else { // adjust class of label to unchecked style, clear checked
                            U.removeClass(objs[i], 'chk');
                            U.addClass(objs[i], 'clr');
                            obj.checked = false;
                        }
                        return true;
                    } else { // initialize on page load
                        if (obj.checked) { // adjust class of label to checked style
                            U.removeClass(objs[i], 'clr');
                            U.addClass(objs[i], 'chk');
                        } else { // adjust class of label to unchecked style
                            U.removeClass(objs[i], 'chk');
                            U.addClass(objs[i], 'clr')
                        }
                    }
                }
            }
          }

          function chk_events(init) {
            var objs = document.getElementsByTagName('INPUT');
            if (typeof init == 'undefined') init = false;
            else init = init ? true : false;
            for(var i = 0; i < objs.length; i++) {
                if (objs[i].type.toLowerCase() == 'checkbox' || objs[i].type.toLowerCase() == 'radio' ) {
                    if (!init) {
                        U.bind_onclick(objs[i], function() {
                            chk_labels(this, init); // bind checkbox click event handler
                        });
                    }
                    else chk_labels(objs[i], init); // initialize state of checkbox onload
                }
            }
          }

          U.bind_onload(function() { // bind window onload event
            chk_events(false); // bind click event handler to all checkboxes
            chk_events(true); // initialize
          });
        </script>

        <div class="green-submit">
          <input type="submit" name="commit" value="Log in" data-disable-with="Log in">
        </div>
</form>
  </div>
</div>




</body></html>

同样,我可能在这里遗漏了一些明显的东西......我是开发新手,而JavaScript是我特别挣扎的东西。我已经阅读了很多资源,但在我看来,代码看起来仍然正确......

显然,我错了......所以任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:2)

使用window.addEventListener而不是覆盖window.onload

errorexplanationcontainer

<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
    window.addEventListener("load", function() {
        var z = document.getElementById("errorexplanationcontainer");
        z.className = "show";
        setTimeout(function() {
            z.className = z.className.replace("show", "");
        }, 3000);
    }, false);
</script>

alert

<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
    window.addEventListener("load", function() {
        var y = document.getElementById("alert")
        y.className = "show";
        setTimeout(function() {
            y.className = y.className.replace("show", "");
        }, 3000);
    }, false);
</script>