了解JavaScript样式

时间:2013-02-03 02:12:17

标签: javascript

在以下代码中,来自“Secrets of the JavaScript Ninja”,为什么“另一个测试”。用红色字体显示?

http://jsfiddle.net/dtHyc/

<html>
  <head>
    <title>Test Suite</title>
    <script>

      (function() {
        var results;
        this.assert = function assert(value, desc) {
          var li = document.createElement("li");
          li.className = value ? "pass" : "fail";
          li.appendChild(document.createTextNode(desc));
          results.appendChild(li);
          if (!value) {
            li.parentNode.parentNode.className = "fail";
          }
          return li;
        };
        this.test = function test(name, fn) {
          results = document.getElementById("results");
          results = assert(true, name).appendChild(
              document.createElement("ul"));
          fn();
        };
      })();

      window.onload = function() {
        test("A test.", function() {
          assert(true, "First assertion completed");
          assert(true, "Second assertion completed");
          assert(true, "Third assertion completed");
        });
        test("Another test.", function() {
          assert(true, "First test completed");
          assert(false, "Second test failed");
          assert(true, "Third assertion completed");
        });
        test("A third test.", function() {
          assert(null, "fail");
          assert(5, "pass")
        });
      };
    </script>
    <style>
      #results li.pass { color: green; }
      #results li.fail { color: red; }
    </style>
  </head>
  <body>
    <ul id="results"></ul>
  </body>
</html>

1 个答案:

答案 0 :(得分:5)

由于字符串是真实的("Second test failed" != false),

assert(false, "Second test failed");

返回false,这会使整个测试失效。