0

I am trying to create a JavaScript Module using the pattern I found here.

I would like to add the onclick event to the <a> element with JavaScript. Each click of the <a> element should hide or show the content div.

Here is a Fiddle to what I have so far: http://jsfiddle.net/66aKc/

Here is the HTML I have:

<a href="#" id="clickHere">Click here to toggle visibility</a>
<div id="foo">This is foo</div>

Here is the CSS I have:

#foo {display:none;}

Here is the JavaScript I have:

var s;
ShowHideWidget = {

  settings : {
    clickHere : document.getElementById('clickHere'),
    foo       : document.getElementById('foo')
  },

  init : function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions : function() {
    s.clickHere.onclick =
        ShowHideWidget.toggleVisibility(s.foo);
  },

  toggleVisibility : function(id) {
    if(id.style.display == 'block') {
      id.style.display = 'none';
    } else {
      id.style.display = 'block';
   };
  }

};

(function() {
  ShowHideWidget.init();
})();

I am not sure why this does not work.

4

1 回答 1

2

当您分配 onclick 处理程序时,您正在执行该函数,而不是将其作为处理程序附加,因此 onclick 成为 toggleVisibility 的返回,它为空。

尝试:

var s;
ShowHideWidget = {

  settings : {
    clickHere : document.getElementById('clickHere'),
    foo       : document.getElementById('foo')
  },

  init : function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions : function() {
    s.clickHere.onclick = function() {
        ShowHideWidget.toggleVisibility(s.foo);
    };
  },

  toggleVisibility : function(id) {
    if(id.style.display == 'block') {
      id.style.display = 'none';
    } else {
      id.style.display = 'block';
   };
  }

};

(function() {
  ShowHideWidget.init();
})();
于 2013-08-15T00:51:03.143 回答