## JS动态添加表单示例 ## ```html ``` ```html $('#month').change(function(){ var m=$(this).val(); var id=$('#userId').val(); var temp = document.createElement("form"); temp.action = "/admin/Article/article_worklog"; temp.method = "post"; temp.style.display = "none"; var month=document.createElement("input"); month.name='month'; month.value=m; temp.appendChild(month); var uid=document.createElement("input"); uid.name='id'; uid.value=id; temp.appendChild(uid); document.body.appendChild(temp); temp.submit(); return temp; }); ``` ## JS封装的ajax函数 ## ```html /* 封装ajax函数 * @param {string}opt.type http连接的方式,包括POST和GET两种方式 * @param {string}opt.url 发送请求的url * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的 * @param {object}opt.data 发送的参数,格式为对象类型 * @param {function}opt.success ajax发送并接收成功调用的回调函数 */ function ajax(opt) { opt = opt || {}; opt.method = opt.method.toUpperCase() || 'POST'; opt.url = opt.url || ''; opt.async = opt.async || true; opt.data = opt.data || null; opt.success = opt.success || function () {}; var xmlHttp = null; if (XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); }var params = []; for (var key in opt.data){ params.push(key + '=' + opt.data[key]); } var postData = params.join('&'); if (opt.method.toUpperCase() === 'POST') { xmlHttp.open(opt.method, opt.url, opt.async); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xmlHttp.send(postData); } else if (opt.method.toUpperCase() === 'GET') { xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async); xmlHttp.send(null); } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { opt.success(xmlHttp.responseText); } }; } ``` 调用代码 ```html ajax({ method: 'POST', url: 'test.php', data: { name1: 'value1', name2: 'value2' }, success: function (response) { console.log(response); } }); ``` ## Jquery返回顶部 ## ```html $("#back-to-top").click(function(){ $('body,html').animate({scrollTop:0},1000); return false; }); ``` ## Js原生无缝向上滚动效果 ## ```php 领取了烈焰双11礼包1、dqx5*** 领取了烈焰双11礼包2、s376*** 领取了街机三国双11礼包3、sdk1*** 领取了烈火战神双11礼包4、说好〃不沋伤 领取了街机三国双11礼包5、说好〃不沋伤 领取了烈焰双11礼包6、gao6*** 领取了街机三国双11礼包7、ando*** 领取了街机三国双11礼包8、6813*** 领取了烈焰双11礼包9、lais*** ``` ## 向上滚动效果自写 ## ```html 新增就业 {$j.name}{$j.xueli}{:cutr($j['gongsi'],3)}月薪{$j.xinzi} ``` ```html ``` ## JS控制H5中的video标签播放暂停 ## ```html 你的浏览器不支持 ``` ## 代替表单中number效果 ## ```php 手机号: ``` ## 判断身份证号 ## ```html 身份证号码的正则表达式及验证详解(JavaScript,Regex)方案2测试 ``` ## JS判断富文本的真实长度 ## ```html var params = $(this).serializeArray(); var values = {}; for(var x in params ) { if(params[x].name=='content'){ values[params[x].name] = CKEDITOR.instances.editor.getData(); var len = 0; var content=values[params[x].name]; var pres = content.match(/(.*?)<\/pre>/g); content= content.replace(/(.*?)<\/pre>/g,""); if(pres) len += pres.join("").length; len += content .replace(/\s+/g," ") //将多个空字符换成一个空格 .replace(//g,".") //将所有换行符替换成一个字符(不用\n是因为可能会被后面换掉) .replace(/(<\/p>)/g,".$1") //为所有段落添加一个字符(或两个字符,自己定)将点放在前面避免影响后面的替换 .replace(/<\/.+?>\s*<[^\/]>/g,"") //去掉所有尾-首相连的HTML标签(包括中间的空字符) .replace(/<.+?>/g,"") //去掉剩下的HTML标签 .replace(/&.+?;/g,".") //转换所有实体为一个字符 .length; if(len <10){ swal({title: "你回复的字数太少", type: "error", timer:1400, showConfirmButton:false,}); return false; } }else{ values[params[x].name] = params[x].value; } ``` ## Js和Jquery选中 ## **js原生选中select的值,设置selected索引的值(相当于select第1个options设置选中)** `var shiting=document.getElementById('shiting');` `shiting.options.selectedIndex=parseInt(1);` **Jquery设置内容为’启东’的text文本为选中** `$("#update_pid").find("option[text='"+result.pid+"']").attr("selected",true);` **JQuery设置value为1的为选中状态** `$("#update_pid").find("option[value='"+result.pid+"']").attr("selected",true);` **jquery获取选中的文本** `$('#pid').find("option:selected").text();` **js原生checked多选款选中** `document.getElementById("u"+[arr[i]]).checked=true;` **JQuery遍历多选框设置false** ```php $("[name='call[]']:checkbox").each(function () { $(this).attr("checked", false); }); ``` ## 缓存 ## ```html ``` JS动态添加表单示例<script type="text/javascript"> function postwith(url, data) { var myForm = document.createElement("form"); myForm.method = "post"; myForm.action = url; for ( var k in data) { var myInput = document.createElement("input"); myInput.setAttribute("name", k); myInput.setAttribute("value", data[k]); myForm.a(myInput); } document.body.a(myForm); myForm.submit(); document.body.removeChild(myForm); } </script> $('#month').change(function(){ var m=$(this).val(); var id=$('#userId').val(); var temp = document.createElement("form"); temp.action = "/admin/Article/article_worklog"; temp.method = "post"; temp.style.display = "none"; var month=document.createElement("input"); month.name='month'; month.value=m; temp.appendChild(month); var uid=document.createElement("input"); uid.name='id'; uid.value=id; temp.appendChild(uid); document.body.appendChild(temp); temp.submit(); return temp; });JS封装的ajax函数/* 封装ajax函数 * @param {string}opt.type http连接的方式,包括POST和GET两种方式 * @param {string}opt.url 发送请求的url * @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的 * @param {object}opt.data 发送的参数,格式为对象类型 * @param {function}opt.success ajax发送并接收成功调用的回调函数 */ function ajax(opt) { opt = opt || {}; opt.method = opt.method.toUpperCase() || 'POST'; opt.url = opt.url || ''; opt.async = opt.async || true; opt.data = opt.data || null; opt.success = opt.success || function () {}; var xmlHttp = null; if (XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); }var params = []; for (var key in opt.data){ params.push(key + '=' + opt.data[key]); } var postData = params.join('&'); if (opt.method.toUpperCase() === 'POST') { xmlHttp.open(opt.method, opt.url, opt.async); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xmlHttp.send(postData); } else if (opt.method.toUpperCase() === 'GET') { xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async); xmlHttp.send(null); } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { opt.success(xmlHttp.responseText); } }; }调用代码ajax({ method: 'POST', url: 'test.php', data: { name1: 'value1', name2: 'value2' }, success: function (response) { console.log(response); } });Jquery返回顶部 $("#back-to-top").click(function(){ $('body,html').animate({scrollTop:0},1000); return false; });Js原生无缝向上滚动效果<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="keywords" content=""> <style> *{margin:0;padding:0} #slide{position:absolute;height:300px;width:260px;color:#FA8E93;overflow:hidden;border:1px solid #ccc} #slide p{height:34px;line-height:34px;overflow:hidden} #slide span{float:right} </style> </head> <body> <div id="slide"> <div id="slide1"> <p><span>领取了烈焰双11礼包</span>1、dqx5***</p> <p><span>领取了烈焰双11礼包</span>2、s376***</p> <p><span>领取了街机三国双11礼包</span>3、sdk1***</p> <p><span>领取了烈火战神双11礼包</span>4、说好〃不沋伤</p> <p><span>领取了街机三国双11礼包</span>5、说好〃不沋伤</p> <p><span>领取了烈焰双11礼包</span>6、gao6***</p> <p><span>领取了街机三国双11礼包</span>7、ando***</p> <p><span>领取了街机三国双11礼包</span>8、6813***</p> <p><span>领取了烈焰双11礼包</span>9、lais***</p> </div> <div id=slide2></div> </div> <script> var speed=40 var slide=document.getElementById("slide"); var slide2=document.getElementById("slide2"); var slide1=document.getElementById("slide1"); slide2.innerHTML=slide1.innerHTML function Marquee(){ if(slide2.offsetTop-slide.scrollTop<=0) slide.scrollTop-=slide1.offsetHeight else{ slide.scrollTop++ } } var MyMar=setInterval(Marquee,speed) slide.onmouseover=function(){clearInterval(MyMar)} slide.onmouseout=function(){MyMar=setInterval(Marquee,speed)} </script> </body> </html>向上滚动效果自写<ul class="Obtain_nr_rt"> <img src="__PUBLIC__/home/index1/img/yts_03.jpg" width="232" height="140"> <h3>新增就业</h3> <ul id="news-container"> <volist name="jiuye" id="j"> <li><a href="javascript:;"><span class="Obt_rt_1">{$j.name}</span><span class="Obt_rt_1">{$j.xueli}</span><span class="Obt_rt_2">{:cutr($j['gongsi'],3)}</span><span class="Obt_rt_3">月薪{$j.xinzi}</span></a></li> </volist> </ul> <script> function ss() { var a=$('#news-container ').children('li:first-child'); var b=$('#news-container ').children('li:first-child'); $(a).animate({marginTop:'-30px'},1000,function(){ $(a).remove(); $(b).css('marginTop','0px'); $('#news-container').append(b); }); }setInterval(ss,1100); </script>JS控制H5中的video标签播放暂停<div class="even-banner" style="position: relative;"> <ol class="main-1200"> <img src="__PUBLIC__/home/zt/yexiao/img/eav_03.png" class="even_vis"> <img src="__PUBLIC__/home/zt/yexiao/img/eav_06.gif" class="even_vis1"> <dl class="even_deo"> <video id="vid" class="video_sp" height="280" width="495;" loop > <source src="__PUBLIC__/home/zt/yexiao/222.mp4" type="video/mp4"> 你的浏览器不支持 </video> </dl> </ol> <img id="play" src="__PUBLIC__/home/zt/yexiao/img/play.png" style="display:block;cursor: pointer;top:500px;left:820px;z-index: 999999;position:absolute;"> <script>//视频播放 var myVideo=document.getElementById('vid'); $('#play').click(function(){ myVideo.play(); $(this).hide(); }); $('#vid').click(function(){ if (myVideo.paused) { myVideo.play(); $('#play').hide(); }else { myVideo.pause(); $('#play').show(); } }); </script>代替表单中number效果手机号:<input type="text" name="phone" id="phone" value="" onkeyup="f(this);"/> <script> function f(obj) { if (!obj.value.match(/^\d+$/)) { if(obj.value==""){obj.value = 0; }else{obj.value = obj.defaultValue;} } else {obj.defaultValue = obj.value;} } </script>判断身份证号<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>身份证号码的正则表达式及验证详解(JavaScript,Regex)方案2测试</title> </head> <body> <div id="main"></div> <script> console.log = function(val) { document.getElementById("main").innerHTML += val +"<br />"; } var checkCode = function (val) { var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]; var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]; var code = val.substring(17); if(p.test(val)) { var sum = 0; for(var i=0;i<17;i++) { sum += val[i]*factor[i]; } if(parity[sum % 11] == code.toUpperCase()) { return true; } } return false; } var checkDate = function (val) { var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/; if(pattern.test(val)) { var year = val.substring(0, 4); var month = val.substring(4, 6); var date = val.substring(6, 8); var date2 = new Date(year+"-"+month+"-"+date); if(date2 && date2.getMonth() == (parseInt(month) - 1)) { return true; } } return false; } var checkProv = function (val) { var pattern = /^[1-9][0-9]/; var provs = {11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门"}; if(pattern.test(val)) { if(provs[val]) { return true; } } return false; } var checkID = function (val) { if(checkCode(val)) { var date = val.substring(6,14); if(checkDate(date)) { if(checkProv(val.substring(0,2))) { return true; } } } return false; } //输出 true console.log(checkID("11010519491231002X")); //输出 false,校验码不符 console.log(checkID("110105194912310021")); //输出 false,日期码不符 console.log(checkID("110105194902310026")); //输出 false,地区码不符 console.log(checkID("160105194912310029")); </script> </body> </html>JS判断富文本的真实长度var params = $(this).serializeArray(); var values = {}; for(var x in params ) { if(params[x].name=='content'){ values[params[x].name] = CKEDITOR.instances.editor.getData(); var len = 0; var content=values[params[x].name]; var pres = content.match(/<pre*.?>(.*?)<\/pre>/g); content= content.replace(/<pre*.?>(.*?)<\/pre>/g,""); if(pres) len += pres.join("").length; len += content .replace(/\s+/g," ") //将多个空字符换成一个空格 .replace(/<br\s*?\/?>/g,".") //将所有换行符替换成一个字符(不用\n是因为可能会被后面换掉) .replace(/(<\/p>)/g,".$1") //为所有段落添加一个字符(或两个字符,自己定)将点放在前面避免影响后面的替换 .replace(/<\/.+?>\s*<[^\/]>/g,"") //去掉所有尾-首相连的HTML标签(包括中间的空字符) .replace(/<.+?>/g,"") //去掉剩下的HTML标签 .replace(/&.+?;/g,".") //转换所有实体为一个字符 .length; if(len <10){ swal({title: "你回复的字数太少", type: "error", timer:1400, showConfirmButton:false,}); return false; } }else{ values[params[x].name] = params[x].value; }Js和Jquery选中js原生选中select的值,设置selected索引的值(相当于select第1个options设置选中)var shiting=document.getElementById('shiting');shiting.options.selectedIndex=parseInt(1);Jquery设置内容为’启东’的text文本为选中$("#update_pid").find("option[text='"+result.pid+"']").attr("selected",true);JQuery设置value为1的为选中状态$("#update_pid").find("option[value='"+result.pid+"']").attr("selected",true);jquery获取选中的文本$('#pid').find("option:selected").text();js原生checked多选款选中document.getElementById("u"+[arr[i]]).checked=true;JQuery遍历多选框设置false$("[name='call[]']:checkbox").each(function () { $(this).attr("checked", false); });缓存<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <title></title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <video id="myvideo" width="100%" height="100%" controls="controls" poster="img/cars.png"> <source src="cars.mp4" type="video/mp4"></source> </video> <script type="text/javascript"> var video = document.getElementById('myvideo'); var currentTime = localStorage.getItem("currentTime"); console.log(currentTime); video.addEventListener("loadedmetadata",function(){ this.currentTime = currentTime; }); video.addEventListener("timeupdate",function(){ var currentTime = Math.floor(video.currentTime); localStorage.setItem("currentTime",currentTime); console.log(localStorage.getItem("currentTime")); }); </script> </body> </html> 最后修改:2020 年 01 月 08 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏 文章引用 反向引用 Loading... 暂未引用其他文章 暂未被其它文章引用 下一篇 上一篇 发表评论 取消回复 使用cookie技术保留您的个人信息以便您下次快速评论,继续评论表示您已同意该条款 评论 * 私密评论 名称 * 🎲 邮箱 * 地址 发表评论 提交中...