angularjs间共享数据

html

<input type="text" ng-model="person.name"/>
  <div ng-controller="FirstCtrl">
  {{person.name}}
  <button ng-click="setName()">set name to jack</button>
  </div>
  <div ng-controller="SecondCtrl">
  {{person.name}}
  <button ng-click="setName()">set name to jack</button>
  </div>
</div>

js

var myApp = angular.module("myApp", []);
myApp.factory('Data', function() {
  return {
    name: "Ting"
  }
});
myApp.controller('FirstCtrl', function($scope, Data) {
  $scope.data = Data;

  $scope.setName = function() {
    Data.name = "Jack";
  }
});

myApp.controller('SecondCtrl', function($scope, Data) {
  $scope.data = Data;

  $scope.setName = function() {
    Data.name = "Moby";
  }
});

angularjs checkbox array

方案一

html

<label ng-repeat="fruitName in fruits">
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruitName}}"
    ng-checked="selection.indexOf(fruitName) > -1"
    ng-click="toggleSelection(fruitName)"
  > {{fruitName}}
</label>

js

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
  // fruits
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];

  // selected fruits
  $scope.selection = ['apple', 'pear'];

  // toggle selection for a given fruit by name
  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    // is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // is newly selected
    else {
      $scope.selection.push(fruitName);
    }
  };
}]);

方案二

html

<label ng-repeat="fruit in fruits">
  <!--
    - use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
      traditionally

    - use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
      (no two-way-data-binding)

    - use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
      is arbitrary. The property name could be anything and will be created on the object if not present.
  -->
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruit.name}}"
    ng-model="fruit.selected"
  > {{fruit.name}}
</label>

js

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {
  // fruits
  $scope.fruits = [
    { name: 'apple',    selected: true },
    { name: 'orange',   selected: false },
    { name: 'pear',     selected: true },
    { name: 'naartjie', selected: false }
  ];

  // selected fruits
  $scope.selection = [];

  // helper method to get selected fruits
  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

  // watch fruits for changes
  $scope.$watch('fruits|filter:{selected:true}', function (nv) {
    $scope.selection = nv.map(function (fruit) {
      return fruit.name;
    });
  }, true);
}]);

AngularJs 父子级Controller传递数据

html代码

<div ng-controller="MyAccountCtrl">

   <div ng-controller="TransferCtrl">
           .............

   </div>

</div>

js代码

// 子级传递数据给父级
// 子级传递
$scope.checkLoggedIn = function(type) {
          $scope.transferType = type;
          $scope.$emit('transfer.type', type);
}

// 父级接收
$scope.$on('transfer.type', function(event, data) {
          $scope.transferType = data;
        });
        $scope.checkLoggedIn = function() {
          var type = $scope.transferType;
}
// 父级传递数据给子级
// 父级传递
$scope.transferType = '';
$scope.checkLoggedIn = function(type) {
          $scope.transferType = type;
          $scope.$broadcast('transfer.type', type);
}

// 子级接收
$scope.transferType = '';
$scope.$on('transfer.type', function(event, data) {
          $scope.transferType = data;
        });
        $scope.checkLoggedIn = function() {
          var type = $scope.transferType;
}

jQuery Validate验证框架详解

jQuery校验官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation 

默认校验规则

(1)、required:true 必输字段
(2)、remote:"remote-valid.jsp" 使用ajax方法调用remote-valid.jsp验证输入值
(3)、email:true 必须输入正确格式的电子邮件
(4)、url:true 必须输入正确格式的网址
(5)、date:true 必须输入正确格式的日期,日期校验ie6出错,慎用
(6)、dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
(7)、number:true 必须输入合法的数字(负数,小数)
(8)、digits:true 必须输入整数
(9)、creditcard:true 必须输入合法的信用卡号
(10)、equalTo:"#password" 输入值必须和#password相同
(11)、accept: 输入拥有合法后缀名的字符串(上传文件的后缀)
(12)、maxlength:5 输入长度最多是5的字符串(汉字算一个字符)
(13)、minlength:10 输入长度最小是10的字符串(汉字算一个字符)
(14)、rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
(15)、range:[5,10] 输入值必须介于 5 和 10 之间
(16)、max:5 输入值不能大于5
(17)、min:10 输入值不能小于10

默认的提示

messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1}."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
},
//如需修改
$.extend($.validator.messages, {
required: "必选字段",
remote: "请修正该字段",
email: "请输入正确格式的电子邮件",
url: "请输入合法的网址",
date: "请输入合法的日期",
dateISO: "请输入合法的日期 (ISO).",
number: "请输入合法的数字",
digits: "只能输入整数",
creditcard: "请输入合法的信用卡号",
equalTo: "请再次输入相同的值",
accept: "请输入拥有合法后缀名的字符串",
maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串"),
minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"),
rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
max: $.validator.format("请输入一个最大为 {0} 的值"),
min: $.validator.format("请输入一个最小为 {0} 的值")
});
//推荐做法,将此文件放入messages_cn.js中,在页面中引入

使用方式 

1、metadata用法,将校验规则写到控件中

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>jQuery Validate验证框架详解-metadata用法</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="/validate/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/validate/jquery.validate.min.js"></script>
<script type="text/javascript" src="/validate/jquery.metadata.min.js"></script>
<script type="text/javascript" src="/validate/messages_zh.js"></script>
<script type="text/javascript">
$(function(){
$("#myform").validate();
});
</script>
</head>

<body>
<form id="myform" method="post" action="">
<p>
<label for="myname">用户名:</label>
<!-- id和name最好同时写上 -->
<input id="myname" name="myname" class="required" />
</p>
<p>
<label for="email">E-Mail:</label>
<input id="email" name="email" class="required email" />
</p>
<p>
<label for="password">登陆密码:</label>
<input id="password" name="password" type="password"
class="{required:true,minlength:5}" />
</p>
<p>
<label for="confirm_password">确认密码:</label>
<input id="confirm_password" name="confirm_password" type="password"
class="{required:true,minlength:5,equalTo:'#password'}" />
</p>
<p>
<label for="confirm_password">性别:</label>
<!-- 表示必须选中一个 -->
<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input type="radio" id="gender_female" value="f" name="gender"/>
</p>
<p>
<label for="confirm_password">爱好:</label>
<!-- checkbox的minlength表示必须选中的最小个数,maxlength表示最大的选中个数,rangelength:[2,3]表示选中个数区间 -->
<input type="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" id="spam_mail" value="mail" name="spam[]" />
</p>
<p>
<label for="confirm_password">城市:</label>
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
<option value=""></option>
<option value="1">厦门</option>
<option value="2">泉州</option>
<option value="3">Oi</option>
</select>
</p>
<p>
<input class="submit" type="submit" value="立即注册" />
</p>
</form>
</body>
</html>
//使用class="{}"的方式,必须引入包:jquery.metadata.js;
//可以使用如下的方法,修改提示内容:class="{required:true,minlength:5,messages:{required:'请输入内容'}}";
//在使用equalTo关键字时,后面的内容必须加上引号,如下代码:class="{required:true,minlength:5,equalTo:'#password'}"。

2、将校验规则写到js代码中

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>jQuery Validate验证框架详解</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="/validate/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/validate/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function(){
var validate = $("#myform").validate({
debug: true, //调试模式取消submit的默认提交功能
//errorClass: "label.error", //默认为错误的样式类为:error
focusInvalid: false, //当为false时,验证无效时,没有焦点响应
onkeyup: false,
submitHandler: function(form){ //表单提交句柄,为一回调函数,带一个参数:form
alert("提交表单");
form.submit(); //提交表单
},

rules:{
myname:{
required:true
},
email:{
required:true,
email:true
},
password:{
required:true,
rangelength:[3,10]
},
confirm_password:{
equalTo:"#password"
}
},
messages:{
myname:{
required:"必填"
},
email:{
required:"必填",
email:"E-Mail格式不正确"
},
password:{
required: "不能为空",
rangelength: $.format("密码最小长度:{0}, 最大长度:{1}。")
},
confirm_password:{
equalTo:"两次密码输入不一致"
}
}

});

});
</script>
</head>

<body>
<form id="myform" method="post" action="">
<p>
<label for="myname">用户名:</label>
<!-- id和name最好同时写上 -->
<input id="myname" name="myname" />
</p>
<p>
<label for="email">E-Mail:</label>
<input id="email" name="email" />
</p>
<p>
<label for="password">登陆密码:</label>
<input id="password" name="password" type="password" />
</p>
<p>
<label for="confirm_password">确认密码:</label>
<input id="confirm_password" name="confirm_password" type="password" />
</p>
<p>
<input class="submit" type="submit" value="立即注册" />
</p>
</form>
</body>
</html>

常用方法及注意问题

1、用其他方式替代默认的submit

$(function(){
$("#signupForm").validate({
submitHandler:function(form){
alert("submit!");
form.submit();
}
});
});
//可以设置validate的默认值,写法如下:
$.validator.setDefaults({
submitHandler: function(form) { alert("submit!"); form.submit(); }
});
//如果想提交表单,需要使用form.submit(),而不要使用$(form).submit()

2、debug,只验证不提交表单 

如果这个参数为true,那么表单不会提交,只进行检查,调试时十分方便

$(function(){
$("#signupForm").validate({
debug:true
});
});
//如果一个页面中有多个表单都想设置成为debug,用
$.validator.setDefaults({
debug: true
})

3、ignore:忽略某些元素不验证
ignore: “.ignore”
4、更改错误信息显示的位置
errorPlacement:Callback
Default: 把错误信息放在验证的元素后面
指明错误放置的位置,默认情况是:error.appendTo(element.parent());即把错误信息放在验证的元素后面
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
//示例

<tr>
<td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
<td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>
<td class="status"></td>
</tr>
<tr>
<td style="padding-right: 5px;">
<input id="dateformat_eu" name="dateformat" type="radio" value="0" />
<label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>
</td>
<td style="padding-left: 5px;">
<input id="dateformat_am" name="dateformat" type="radio" value="1" />
<label id="ldateformat_am" for="dateformat_am">02/14/07</label>
</td>
<td></td>
</tr>
<tr>
<td class="label">&nbsp;</td>
<td class="field" colspan="2">
<div id="termswrap">
<input id="terms" type="checkbox" name="terms" />
<label id="lterms" for="terms">I have read and accept the Terms of Use.</label>
</div>
</td>
</tr>

errorPlacement: function(error, element) {
if (element.is(":radio"))
error.appendTo(element.parent().next().next());
else if (element.is(":checkbox"))
error.appendTo(element.next());
else
error.appendTo(element.parent().next());
}

代码的作用是:一般情况下把错误信息显示在中,如果是radio显示在中,如果是checkbox显示在内容的后面
errorClass:String Default: “error”
指定错误提示的css类名,可以自定义错误提示的样式
errorElement:String Default: “label”
用什么标签标记错误,默认的是label你可以改成em
errorContainer:Selector
显示或者隐藏验证信息,可以自动实现有错误信息出现时把容器属性变为显示,无错误时隐藏,用处不大
errorContainer: “#messageBox1, #messageBox2”
errorLabelContainer:Selector
把错误信息统一放在一个容器里面。
wrapper:String
用什么标签再把上边的errorELement包起来
一般这三个属性同时使用,实现在一个容器内显示所有错误提示的功能,并且没有信息时自动隐藏
errorContainer: “div.error”,
errorLabelContainer: $(“#signupForm div.error”),
wrapper: “li”

5、更改错误信息显示的样式 

设置错误提示的样式,可以增加图标显示,在该系统中已经建立了一个validation.css专门用于维护校验文件的样式

input.error { border: 1px solid red; }
label.error {
background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
padding-bottom: 2px;
font-weight: bold;
color: #EA5200;
}
label.checked {
background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}

6、每个字段验证通过执行函数
success:String,Callback
要验证的元素通过验证后的动作,如果跟一个字符串,会当做一个css类,也可跟一个函数

success: function(label) {
// set &nbsp; as text for IE
label.html("&nbsp;").addClass("checked");
//label.addClass("valid").text("Ok!")
}
//添加"valid"到验证元素, 在CSS中定义的样式<style>label.valid {}</style>
//success: "valid"

7、验证的触发方式修改
下面的虽然是boolean型的,但建议除非要改为false,否则别乱添加。
a.onsubmit:Boolean Default: true
提交时验证. 设置唯false就用其他方法去验证
b.onfocusout:Boolean Default: true
失去焦点是验证(不包括checkboxes/radio buttons)
c.onkeyup:Boolean Default: true
在keyup时验证.
d.onclick:Boolean Default: true
在checkboxes 和 radio 点击时验证
e.focusInvalid:Boolean Default: true
提交表单后,未通过验证的表单(第一个或提交之前获得焦点的未通过验证的表单)会获得焦点
f.focusCleanup:Boolean Default: false
如果是true那么当未通过验证的元素获得焦点时,移除错误提示。避免和focusInvalid一起用

8、异步验证 

remote:URL 

使用ajax方式进行验证,默认会提交当前验证的值到远程地址,如果需要提交其他的值,可以使用data选项

示例一:
remote: "check-email.php"
示例二:
remote: {
url: "check-email.php", //后台处理程序
type: "post", //数据发送方式
dataType: "json", //接受数据格式
data: { //要传递的数据
username: function() {
return $("#username").val();
}
}
}
//远程地址只能输出"true"或"false",不能有其它输出。

9、添加自定义校验
addMethod:name, method, message
自定义验证方法
1.要在additional-methods.js文件中添加或者在jquery.validate.js添加
建议一般写在additional-methods.js文件中
2.在messages_cn.js文件添加:isZipCode: “只能包括中文字、英文字母、数字和下划线”,
调用前要添加对additional-methods.js文件的引用。

// 中文字两个字节
jQuery.validator.addMethod(
"byteRangeLength",
function(value, element, param) {
var length = value.length;
for(var i = 0; i < value.length; i++){
if(value.charCodeAt(i) > 127){
length++;
}
}
return this.optional(element) || (length >= param[0] && length <= param[1]);
},
$.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)")
);

// 邮政编码验证
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");

10、radio和checkbox、select的验证

1.radio的required表示必须选中一个
<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input type="radio" id="gender_female" value="f" name="gender"/>

2.checkbox的required表示必须选中
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />

checkbox的minlength表示必须选中的最小个数,maxlength表示最大的选中个数,rangelength:[2,3]表示选中个数区间
<input type="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" id="spam_mail" value="mail" name="spam[]" />

3.select的required表示选中的value不能为空
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
<option value=""></option>
<option value="1">Buga</option>
<option value="2">Baga</option>
<option value="3">Oi</option>
</select>

select的minlength表示选中的最小个数(可多选的select),maxlength表示最大的选中个 数,rangelength:[2,3]表示选中个数区间
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
<option value="b">Banana</option>
<option value="a">Apple</option>
<option value="p">Peach</option>
<option value="t">Turtle</option>
</select>

转自: jQuery Validate验证框架详解

JavaScript提取数组内所有元素

var arrN = [[[1, "wangyuchu", 54, [123, 34, [123, 34, 16]]],"zhangsan", 25, [1, "wangyuchu", 54, [123, 34, [123, 34, [1, "wangyuchu", 54, [123, 34, [123, 34, 16]]],]]], 43], ["lisi", 21, 172], ["wangwu", 32, "suzhou"]];

var arrgroup=[];
function recursion(obj) {
    if (typeof obj==='object') {
        for (var j in obj) {
            if (typeof obj[j]!=='object') {
                arrgroup.push(obj[j]);
                continue;
            }
            recursion(obj[j]);
        }
    } else {
        arrgroup.push(obj);
    }
    return arrgroup;
}
console.log(recursion(arrN));

canvas礼花小程序

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body style="  background-color: #000;">
<canvas id="canvas"></canvas>

<script>
window.requestAnimFrame = ( function() {
    return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                function( callback ) {
                    window.setTimeout( callback, 1000 / 60 );
                };
})();
var canvas = document.getElementById( 'canvas' ),
        ctx = canvas.getContext( '2d' ),
        cw = window.innerWidth,
        ch = window.innerHeight,
        fireworks = [],
        particles = [],
        hue = 120,
        limiterTotal = 5,
        limiterTick = 0,
        timerTotal = 80,
        timerTick = 0,
        mousedown = false,
        mx,
        my;
        
canvas.width = cw;
canvas.height = ch;  

function random( min, max ) {
    return Math.random() * ( max - min ) + min;
}

function calculateDistance( p1x, p1y, p2x, p2y ) {
    var xDistance = p1x - p2x,
            yDistance = p1y - p2y;
    return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}

function Firework( sx, sy, tx, ty ) {
    
    this.x = sx;
    this.y = sy;
    
    this.sx = sx;
    this.sy = sy;
    
    this.tx = tx;
    this.ty = ty;
    
    this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
    this.distanceTraveled = 0;
    
    this.coordinates = [];
    this.coordinateCount = 3;
    
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    this.angle = Math.atan2( ty - sy, tx - sx );
    this.speed = 2;
    this.acceleration = 1.05;
    this.brightness = random( 50, 70 );
    
    this.targetRadius = 1;
}


Firework.prototype.update = function( index ) {
    
    this.coordinates.pop();
    
    this.coordinates.unshift( [ this.x, this.y ] );
    
    if( this.targetRadius < 8 ) {
        this.targetRadius += 0.3;
    } else {
        this.targetRadius = 1;
    }
    
    this.speed *= this.acceleration;
    
    var vx = Math.cos( this.angle ) * this.speed,
            vy = Math.sin( this.angle ) * this.speed;
    
    this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
    
    if( this.distanceTraveled >= this.distanceToTarget ) {
        createParticles( this.tx, this.ty );
        fireworks.splice( index, 1 );
    } else {
        this.x += vx;
        this.y += vy;
    }
}

Firework.prototype.draw = function() {
    ctx.beginPath();
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
    ctx.stroke();
    
    ctx.beginPath();
    ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
    ctx.stroke();
}

function Particle( x, y ) {
    this.x = x;
    this.y = y;
    
    this.coordinates = [];
    this.coordinateCount = 5;
    while( this.coordinateCount-- ) {
        this.coordinates.push( [ this.x, this.y ] );
    }
    
    this.angle = random( 0, Math.PI * 2 );
    this.speed = random( 1, 10 );
    
    this.friction = 0.95;
    this.gravity = 1;
    
    this.hue = random( hue - 20, hue + 20 );
    this.brightness = random( 50, 80 );
    this.alpha = 1;
    this.decay = random( 0.015, 0.03 );
    //this.decay = 0;
}

Particle.prototype.update = function( index ) {
    
    this.coordinates.pop();
    this.coordinates.unshift( [ this.x, this.y ] );
    this.speed *= this.friction;
    this.x += Math.cos( this.angle ) * this.speed;
    this.y += Math.sin( this.angle ) * this.speed + this.gravity;
    this.alpha -= this.decay;
    
    if( this.alpha <= this.decay ) {
        particles.splice( index, 1 );
    }
}

Particle.prototype.draw = function() {
    ctx. beginPath();
    ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
    ctx.lineTo( this.x, this.y );
    ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
    ctx.stroke();
}

function createParticles( x, y ) {
    var particleCount = 30;
    while( particleCount-- ) {
        particles.push( new Particle( x, y ) );
    }
}


function loop() {
    requestAnimFrame( loop );
    
    hue += 0.5;
    
    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect( 0, 0, cw, ch );
    ctx.globalCompositeOperation = 'lighter';
    
    var i = fireworks.length;
    while( i-- ) {
        fireworks[ i ].draw();
        fireworks[ i ].update( i );
    }
    
    var i = particles.length;
    while( i-- ) {
        particles[ i ].draw();
        particles[ i ].update( i );
    }
    
    if( timerTick >= timerTotal ) {
        if( !mousedown ) {
            fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
            timerTick = 0;
        }
    } else {
        timerTick++;
    }
    
    if( limiterTick >= limiterTotal ) {
        if( mousedown ) {
            fireworks.push( new Firework( cw / 2, ch, mx, my ) );
            limiterTick = 0;
        }
    } else {
        limiterTick++;
    }
}

canvas.addEventListener( 'mousemove', function( e ) {
    mx = e.pageX - canvas.offsetLeft;
    my = e.pageY - canvas.offsetTop;
});

canvas.addEventListener( 'mousedown', function( e ) {
    e.preventDefault();
    mousedown = true;
});

canvas.addEventListener( 'mouseup', function( e ) {
    e.preventDefault();
    mousedown = false;
});

window.onload = loop;
</script>
</body>
</html>

AJAX文件上传

var fileObj = document.getElementById('file').files[0];
    // js 获取文件对象
    var FileController = url;
    // 接收上传文件的后台地址

    // FormData 对象
    var form = new FormData();
    form.append("author", "test");
    // 可以增加表单数据
    form.append("file", fileObj);
    // 文件对象

    // XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();
    xhr.open("post", FileController, true);
    xhr.responseType = 'text';
    xhr.onload = function() {
        if (this.status == 200) {
            console.log(this.response);
            var result = JSON.parse(this.response);
            if (result.status) {
                $('#progressBar').hide();
                $('#percentage').hide();
                alert('DXF文件上传完成,系统即将重新加载!');
                sys.init();
            } else {
                console.log('error:' + result.message)
            }
        }
    };
    xhr.upload.addEventListener("progress", progressFunction, false);
    xhr.send(form);

js常用函数

//js 中的算术运算
Math.pow(2,53)      // => 9007199254740992: 2 的 53次幂  
Math.round(.6)      // => 1.0: 四舍五入  
Math.ceil(.6)       // => 1.0: 向上求整  
Math.floor(.6)      // => 0.0: 向下求整  
Math.abs(-5)            // => 5: 求绝对值  
Math.max(x,y,z)         // 返回最大值  
Math.min(x,y,z)         // 返回最小值  
Math.random()       // 生成一个大于等于0小于1.0的伪随机数  
Math.PI             // π: 圆周率  
Math.E              // e: 自然对数的底数  
Math.sqrt(3)            // 3的平方根  
Math.pow(3, 1/3)        // 3的立方根  
Math.sin(0)             // 三角函数: 还有Math.cos, Math.atan等  
Math.log(10)            // 10的自然对数  
Math.log(100)/Math.LN10     // 以10为底100的对数  
Math.log(512)/Math.LN2  // 以2为底512的对数  
Math.exp(3)             // e的三次幂

//js 日期和时间
var then = new Date(2011, 0, 1); // 2011年1月1日  
var later = new Date(2011, 0, 1, 17, 10, 30);// 同一天, 当地时间5:10:30pm,  
var now = new Date(); // 当前日期和时间  
var elapsed = now - then; // 日期减法:计算时间间隔的毫秒数  
later.getFullYear() // => 2011  
later.getMonth() // => 0: 从0开始计数的月份  
later.getDate() // => 1: 从1开始计数的天数  
later.getDay() // => 5: 得到星期几, 0代表星期日,5代表星期一  
later.getHours() // => 当地时间17: 5pm  
later.getUTCHours() // 使用UTC表示小时的时间,基于时区
later.toString() //"Tue Dec 22 2015 15:22:50 GMT+0800 (中国标准时间)"
new Date(later.toString()) //Tue Dec 22 2015 15:22:50 GMT+0800 (中国标准时间)
//时间加60秒
var time = new Date()
time.setTime(time.getTime() + 60000)

//js 字符串处理
var s = "hello, world"  // 定义一个字符串  
s.charAt(0)             // => "h": 第一个字符  
s.charAt(s.length-1)        // => "d": 最后一个字符  
s.substring(1,4)        // => "ell":第2~4个字符  
s.slice(1,4)            // => "ell": 同上  
s.slice(-3)             // => "rld": 最后三个字符  
s.indexOf("l")      // => 2: 字符l首次出现的位置  
s.lastIndexOf("l")      // => 10:字符l最后一次出现的位置  
s.indexOf("l", 3)       // => 3:在位置3及之后首次出现字符l的位置  
s.split(", ")       // => ["hello", "world"] 分割成子串  
s.replace("h", "H")         // => "Hello, world": 全文字符替换  
s.toUpperCase()

按回车不提交,表单验证,验证之后提交

<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $('form').submit(function () {
         return false;
    });
    $(document).keyup(function(event){
        if (event.keyCode == 13){
            if (true) {//逻辑判断
                document.forms[0].submit();
            }
        }
    });
})
</script>
<form id='myform'>
<input type="text">
<input type="submit">
</form>