[英]Javascript change variable using buttons
我试图使用jquery创建一个按钮打开另一个窗口。
按钮应该能够打开窗口。 然后应使用相同的按钮关闭窗口。 我似乎遇到的问题似乎是在按钮打开窗口后没有设置我的变量。 我是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>
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;
}
});
您的状况需要在每次点击时运行 - 不仅仅是一次,在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)你好像两次动画不透明度(一次到.4,同时,到1)所以,为了这个演示的目的,我完全删除了对它的引用。
2)除非你需要设置部分不透明度(而不是0或1)的动画,否则使用jQuery的fadeIn()
和fadeOut()
方法会更容易。
3)设置width: 000
与width: 0
相同width: 0
。
4)避免使用var名称中的大写字母 - 大写字母通常用于表示构造函数。
5)使用double equals测试0
和1
值时要小心,因为truthy / falsy值的概念会让你感到惊讶。 不确定,使用===
not ==
进行测试始终是最安全的。
6)虽然click
很好,但jQuery 1.7引入了它的凌乱事件API的整理,所以你现在可以使用on()
和off()
。 click()
和其他只是别名,在幕后委托给on()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.