为什么这个函数的else部分不会执行?

时间:2014-12-18 00:50:47

标签: javascript jquery if-statement this control-flow

笔是here

当根据两个元素的类的存在点击链接/按钮时,我有两个元素设置来改变宽度,增加或减少。只有if函数中if...else的{​​{1}}部分似乎正在运行。抽屉打开但随后在触发元素的后续点击时不会关闭,尽管通过单击触发元素仍然可以成功地来回更改类。

我在这里缺少什么?感谢。

javascript与jquery

.toggle

HTML

    var container = document.getElementById('container');

    container.widthOpen = '800px';
    container.widthClosed = '210px';

    container.isOpen = function() {
      return this.classList.contains('open');
    };

    container.toggle = function() {
      this.classList.toggle('open');
      if (this.isOpen) {
        $(this).animate({
          width: container.widthOpen
        });
      } else {
        $(this).animate({
          width: container.widthClosed
        });
      }
    };

    var drawer = document.getElementById('drawer');

    drawer.widthOpen = '600px';
    drawer.widthClosed = '10px';

    drawer.isOpen = function() {
      return this.classList.contains('open');
    };

    drawer.toggle = function() {
      this.classList.toggle('open');
      if (this.isOpen) {
        $(this).animate({
          width: drawer.widthOpen
        });
      } else {
        $(this).animate({
          width: drawer.widthClosed
        });
      }
    };

    $('#toggle').click(function() {
      drawer.toggle();
      container.toggle();
    });

CSS

    <div id="container">
      <section id="main">
        <p id="static">
          This should be static.
        </p>
      </section>
      <section id="drawer">
        <div id="wrapper">
          <blockquote id="filler-text" cite="http://genius.com/The-pharcyde-passin-me-by-lyrics/">
            <p>Now in my younger days I used to sport a shag</p>
            <p>When I went to school I carried lunch in a bag</p>
            <p>With an apple for my teacher cause I knew I'd get a kiss</p>
            <p>Always got mad when the class was dismissed</p>
            <footer>
              -
              <cite>
                <a href="http://genius.com/The-pharcyde-passin-me-by-lyrics/">
                  The Pharcyde
                </a>
              </cite>
            </footer>
          </blockquote>
        </div>
      </section>
      <a href="#0" id="toggle">
        Toggle right-side section open/closed
      </a>
    </div>

1 个答案:

答案 0 :(得分:6)

 if (this.isOpen) {

this.isOpen是一个功能。只要函数存在(它确实存在),这就使条件成立。

this.isOpen()将是调用该函数的返回值。