开发者

Javascript toggle issue

This is my script :

window.onload = function (){  
   var title = document.getElementsByTagName('h1')[0].id = "heading1";  
   document.getElementById(title).onclick = function (e){  
          var para = this.nextSibling.style.display = 'block';  
          var newVal = (para == "block") ? "none" : "block";  
          alert(newVal);  
   }  
}  

The result I need is for the alert value to toggle from block to none and back. But I am always getting "none". What is the problem wi开发者_开发知识库th my code?


window.onload = function () {
  var firstH1 = document.getElementsByTagName('h1')[0];
  firstH1.id = "heading1";
  firstH1.onclick = function() {
    var currentValue = this.nextSibling.style.display;
    this.nextSibling.style.display = (currentValue == "none") ? "block" : "none";
  }
} 

Note a few things: I simplified your element fetching because it doesn't make sense to fetch an element, assign it an id, then use that id to find that same element again.

I also switched block/none ordering, because if no style is displayed then it would be blank -- and your first click would assign block to it - and it would not disappear. This way it does.


Well, para will always be "block", and therefore newVal will always be "none". So that behavior is expected. What are you trying to do? you are not toggling the property with your curent code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜