2012-08-23 108 views
1

我正在尝试使用jquery打开另一个窗口的按钮。使用按钮的Javascript更改变量

该按钮应该能够打开窗口。然后应该使用相同的按钮关闭窗口。我似乎遇到的问题表明,在按钮打开窗口后,我的变量没有被设置。我对JavaScript和jquery非常陌生,所以我不确定我是否做错了什么。

<html> 
    <head> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript"> 
     var FileEdit = 0; 
     $(document).ready(function(){ 
     if (FileEdit == 0) 
     { 
      $("button").click(function(){ 
      $("div").animate({opacity:0.4},"fast"); 
      $("div").animate({height:300,width:300},"slow"); 
      $("div").animate({opacity:1},"slow"); 
      FileEdit = 1; 
      }); 
     } 
     if (FileEdit == 1) 
     { 
      $("button").click(function(){ 
       $("div").animate({height:000,width:000},"slow"); 
       FileEdit = 0; 
      }); 
     } 
     }); 
    </script> 
    </head> 

    <body> 
     <button>Start Animation</button> 
     <br /><br /> 
     <div style="background:#98bf21;height:000px;width:000px;"> 
     </div> 
    </body> 
</html> 

http://jsfiddle.net/tqpTE/

+0

你应该链接所有的动画调用,或者把'$(“div”)'放在一个变量中。 – Krycke

+0

@Krycke我不确定你的意思。你能为我解释一些吗? –

+0

当您在每行上使用'$(“div”)'时,jQuery将搜索所有div元素三次。通过使用'var divs = $(“div”);'你可以在其他行上使用该变量,并且只需要一次查找,或者像'$(“div”)一样使用链接。doSomthing()。doSomethingElse(); ' – Krycke

回答

3

jsFiddle DEMO

var FileEdit = 0; 

$("button").on('click', function(){ 

    // You only need one on('click') function 
    // Test for FileEdit here & do whatever you need 

    if (FileEdit === 0) { 

     // Also having those 3 animations right in a row won't make them 
     // go one - after - another. You need to use callback functions 
     // to start the next animation after the previous one finished. 

     $("div").animate({opacity:0.4},"fast", //callback1 
      function() { $(this).animate({height:300,width:300},"slow", //callback2 
       function() { $("div").animate({opacity:1},"slow"); } 
      )} 
     ); 
     FileEdit = 1; 
    } 

    else { 
     $("div").animate({height:000,width:000},"slow"); 
     FileEdit = 0; 
    } 
}); 

More info on .animate() callback functions

1

你的情况需要在每次点击运行 - 不只是一次,DOM的准备,因为目前。另外请注意你的代码可以相当大幅度地减少到这样的事情:

var fileEdit = 0; 
$(function(){ 
    $("button").on('click', function() { 
     var anim_data = !fileEdit ? {width: 300, height: 300} : {width: 0, height: 0}; 
     $("div").animate(anim_data, 'slow'); 
     fileEdit = !fileEdit ? 1 : 0; 
    }); 
}); 

的几个注意事项:

1)你似乎两次(一次动画不透明度为1.4,并且,同时,对1)因此,为了演示的目的,我完全删除了对它的引用。 2)除非你需要动画到部分不透明(而不是0或1),否则更容易使用jQuery的fadeIn()和​​方法。

3)设置width: 000width: 0相同。

4)避免var名称中的大写字母 - 大写字母通常用于表示构造函数。

5)使用double等于01的值进行测试时要小心,因为the concept of truthy/falsy values会让您有些意外。不确定的是,用===而不是==进行测试总是最安全的。

6)虽然click没问题,但jQuery 1.7引入了一个整洁的事件API,所以你现在可以使用on()off()click()和其他只是别名,在幕后,代表on()