(1)即时搜索的输入框监听事件input propertychange
KaTeX parse error: Expected '}', got 'EOF' at end of input: …nction(){
if(("#username").val()!="" && $("#password").val()!=""){
$("#loginSubmit").css(“background”,"#41a5e5");
}
});
(2)60s倒计时
(3)禁用滚动条
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲submit").click(…(window).scrollTop();
$(".gray_screen").css(“top”,scrollTop);
//禁用滚动条
$(document.body).css({ “overflow-y”: “hidden”});
});
//弹窗里的关闭按钮或者取消按钮要设置的属性
//启用滚动条
$(document.body).css({ “overflow-y”: “auto” });
(4)异步加载 仿淘宝购物车结算栏效果
购物车里的东西
(5)jquery写锚链接滑动效果
css
ul{position:fixed;top:0;background:#999999;}
ul li{float:left;margin:10px;padding:10px;}
js
$(function(){
$(“ul li a”).click(function(){
var hr = $(this).attr(“href”);
var anh = $(hr).offset().top;
$(“html,body”).stop().animate({scrollTop:anh},2000);
})
})
html
(6)多个标签的得到失去焦点事件
$(" input[type=text]").focus(function(){
$(this).parent().addClass(“on03”);
}).blur(function(){
$(this).parent().addClass(“on03”);
});
(7)宽度不确定的图片在div(width=1000px)里居中显示
$(“img”).on(‘load’, function(){
var w=this.width;
w=(1000-w)/2;
$(".wynv-pic").css(“margin-left”,w);
}).on(‘error’, function(){
console.error(‘load error’);
});
(8)更多文字的展开收起效果
html
节目介绍文字
(10)动态加载标签
(11)ul写的下拉列表框
html
- 单曲
- 视频
- 艺术家
- 音乐知识
- 有声读物
(12)问题:事件链断掉。web,安卓都生效;ios失效了
http://ms.kuke.com/#index?mac=cc:79:cf:0e:0a:38
方法:给页面上面蒙一个层
答案:
$(’
top:0,
left:0,
width: ‘100%’,
height: ‘100%’,
position: ‘fixed’,
zIndex: 9999999
}).on(‘touchstart’, function() {
var player = jQuery("#jquery_jplayer");
player.jPlayer(“play”);
player.jPlayer(“pause”);
KaTeX parse error: Expected 'EOF', got '把' at position 19: …is).remove();//把̲添加的div删掉 }).app…(‘body’));
(13)鼠标划过和点击时字体都变蓝色
html
- one
- two
- three
- four
(14)输入框只能是输入数字不能输入其他字符的
(15)创建localStorage对象
var localStorage = window.localStorage;
var noList = [{
composer: “composer”,
title: “Track title”,
cover: “/static/i/empty-album.png”,
artist: “Artist”,
brand: “Label”
}];
localStorage.setItem(“musicList”,JSON.stringify(noList));
var smusic = new SMusic({
musicList: JSON.parse(localStorage.getItem(“musicList”))
});
(16)动态获取图片失败时显示默认图片
(17)js数组合并
(1)concat()
var a=[1,2,3],b=[4,5,6];
==>a.concat(b);//得到1,2,3,4,5,6;
==>可以利用这个来复制一份数组,a.concat(a);
==>数组长度无限制,返回值是合并后的数组
(2)Array.prototype.push.apply()
==>Array.prototype.push.apply(a,b)或 a.push.apply(a,b);
==>Array.prototype.push.apply(a,b) ;//a,b两个数组都变成合并后的新数组
==>返回值是合并后数组的长度
(18)call及apply
要先明白存在call和apply的原因,才能记得牢一点:
在javascript OOP()中,经常会这样定义:
//创建构造函数
function Cat(){
}
cat.prototype={
food:“fish”,
say:function(obj){//回调函数
alert(“I love”+this.food);
}
}
//使用构造函数
var blackCat = new Cat;
blackCat.say();//使用构造函数的方法
但是如果我们有一个对象whiteDog = {food:“bone”},我们不想对它重新定义say方法,那么我们可以通过call或apply用blackCat的say方法:blackCat.say.call(whiteDog);所以,可以看出call和apply是为了动态改变this而出现的,当一个object没有某个方法,但是其他的有,我们可以借助call或apply用其它对象的方法来操作。
另外,当我们以{}方式创建对象时,实际上也调用了Object()构造函数。
例如 var obj= {};
(19)在构造函数里自定义事件(去参数)
function Test(){
}
Test.prototype={
musicList:[],
defaultMode:1,
on:function(name,fn){
if(typeof fn === ‘function’){
if(!this.config.functions[name]){
this.config.functions[name] = [];
}
this.config.functions[name].push(fn);
}else{
var fs = this.config.functions[name];
if(fs){
for(var i = 0; i<fs.length; i++){
fs[i].apply(this, fn);
}
}
}
}
}
var t=new Test()
t.on(“play”,function(){
alert(“在此写自定义事件”);
})
t.on(“play”);
可以在构造函数Test()里自定义事件(带参数)
function Test(){
this.config ={
musicList:[],
defaultMode:1,
functions:{}//回调函数
};
}
Test.prototype.on = function (name, fn) {
if(typeof fn === ‘function’){
if(!this.config.functions[name]){
this.config.functions[name] = [];
}
this.config.functions[name].push(fn);
}else{
var fs = this.config.functions[name];
if(Object.prototype.toString.call(fn) !== ‘[object Array]’){
fn = [];
}
if(fs){
for(var i = 0; i < fs.length; i++){
fs[i].apply(this, fn);
}
}
}
}
使用构造函数
var t = new Test();
自定义一个带参数的事件test.event
t.on(‘test.event’, function(a,b,c){
console.log(a,b,c);
});
使用这个定义的事件
t.on(‘test.event’, [1,2,3,4]);
function Test(){
this.config ={functions:{}};
}
Test.prototype.on = function (name, fn) {
if(typeof fn === ‘function’){
if(!this.config.functions[name]){
this.config.functions[name] = [];
}
this.config.functions[name].push(fn);
}else{
var fs = this.config.functions[name];
var args = Array.prototype.slice.call(arguments, 1);
if(args.length == 1 && Object.prototype.toString.call(args[0]) === ‘[object Array]’){
args = args[0];
}
if(fs){
for(var i = 0; i < fs.length; i++){
fs[i].apply(this, args);
}
}
}
}
Test.prototype.test = function (name, fn) {
this.on(‘test.event’, [1,2,3,4]);
}
var t = new Test();
t.on(‘test.event’, function(a,b,c){
console.log(a,b,c);
});
t.on(‘test.event’, [1,2,3,4]);
t.on(‘test.event’, 1,2,3,4);
将函数的参数转换为数组
var args = Array.prototype.slice.call(arguments, 1);
//因为 slice是 array类的方法
//而传进来的参数是一个 DOM对象的数组
//所以通过call 方法把 array类的方法放到这个对象里面执行
//call 的第二个参数是表示向被调用的方法传进参数
/这里的1 表示从index为1的地方开始
判断函数类型
Object.prototype.toString.call(args[0]) === ‘[object Array]’
$0.classList.contains(‘mode’)//判断是否有’mode’这个类
->true
(21)dom倒序排列
- 1
- 2
- 3
- 4
- 5
用法一:防止重复数据
// 提交表单数据到后台处理
$.ajax({
type: “post”,
data: studentInfo,
contentType: “application/json”,
url: “/Home/Submit”,
beforeSend: function () {
// 禁用按钮防止重复提交
$("#submit").attr({ disabled: “disabled” });
},
success: function (data) {
if (data == “Success”) {
//清空输入框
clearBox();
}
},
complete: function () {
$("#submit").removeAttr(“disabled”);
},
error: function (data) {
console.info("error: " + data.responseText);
}
});
用法二:模拟Toast效果:数据加载完成之前显示加载图片效果
$.ajax({
url : “/naxos/?catCategoryId=” + catCategoryId + “&aleph=” + aleph,
type : “get”,
beforeSend : function(){
$("#waiting-img").show();
},
success : function(data){
$("#waiting-img").hide();
// 显示专辑
$("#catalogueTable").html(getPersonCata(data.catalogues));
},
complete: function () {
$(“loading”).hide();
},
error: function (data) {
console.info("error: " + data.responseText);
}
});
(23)遍历数组和json
一。遍历数组
var anArray = [‘one’,‘two’,‘three’];
$.each(anArray,function(index,value){
console.log(“索引”+index+“对应的值”+value);
});
二。json
1.json对象
packJson = {“name”:“caibaojian.com”, “password”:“111”}
遍历json对象
var anObject = {one:1,two:2,three:3,four:4,five:5};
方法一:
$.each(anObject,function(key,value) {
console.log(“关键字”+key+“对应的值”+value);
});
方法二:
for(var p in anObject){
console.log(p+’:’+anObject[p])
}
2.json数组
遍历无规律的json数组
var json = [{dd:‘SB’,AA:‘东东’,re1:123},{cccc:‘dd’,lk:‘1qw’},{cccc:‘dd’,lk:‘1qw’}];
for(var i = 0; i<=json.length; i++){
for(var key in json[i]){
console.log(key+’:’+json[i][key]);
}
}
遍历规则的json数组
var json = [{‘name’:‘my’,‘password’:‘111’,‘sex’:‘girl’},{‘name’:‘wc’,‘password’:‘222’,‘sex’:‘boy’}];
方法一:
for(var p in json){ //p为索引0,1,2
var str = json[p].name+’ ‘+json[p].password+’ ‘+json[p].sex;
console.log(str);
}
方法二:
for(var i = 0; i<=json.length; i++){
var str = json[p].name+’ ‘+json[p].password+’ '+json[p].sex;
console.log(str);
}
(24)jquery-ui 解决刷新页面时重复执行方法
/**
-
folder 下拉框的数据填充
-
@param selector [String] 弹出框选择器
-
@param categoryId [String] tab Id
-
*/
function fetchFolderList(selector, categoryId) {
var $selector = $(selector);
$.ajax({
url: “/naxos/playlist/folderlistbytab?category=” + categoryId,
type: “GET”,
success : function (data) {
var $selectorCategory = $selector.find(’.jsPopSelectCategory’);
var optionStr = ‘’;
$selectorCategory.html("");
for (var i = 0; i< data.length; i++) {
var option = ‘’ + data[i].groupname + ‘’;
optionStr += option;
}
$selectorCategory.html(optionStr).selectmenu().selectmenu(“refresh”);}
});
}
// tab下拉框的change事件
//添加一个属性data-selectmenu用来解决下拉框选择回退按钮时重复添加样式
if($("#tab .tablist .jsPopSelect").attr(‘data-selectmenu’)){
return;
}
$("#tab .tablist .jsPopSelect").attr(‘data-selectmenu’, true).selectmenu({
change: function () {
var tab = $(this).val();
fetchFolderList(’#tab’, tab);
}
});
(25)秒数和时分秒互换
/***
- 时分秒格式的时间转成秒数
- @param time
- @returns {number}
/
function formatToSeconds(time) {
var regTime = /^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/;
if (time.match(regTime)){
var array = time.split(":");
var hour = parseInt(array[0]);
var minute = parseInt(array[1]);
var second = parseInt(array[2]);
return hour3600 + minute60 + second;
} else {
return 0;
}
}
/** - 秒数转换成时分秒的格式
- @param value 秒数
- @returns {string} 格式: HH:mm:ss
*/
function formatSeconds(value) {
if (value == null || value == “”){
return “0:0:0”;
}
if (!isNaN(value)){
var theTime = parseInt(value); // 秒
var theTime1 = 0; // 分
var theTime2 = 0; // 小时
if (theTime > 60) {
theTime1 = parseInt(theTime / 60);
theTime = parseInt(theTime % 60);
if (theTime1 > 60) {
theTime2 = parseInt(theTime1 / 60);
theTime1 = parseInt(theTime1 % 60);
}
}
var result = theTime2 + “:” + theTime1 + “:” + theTime;
return result;
} else {
return “0:0:0”;
}
}
(26)时间戳转换为普通日期格式
function formatDate(timestamp) {
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
Y = date.getFullYear() + ‘-’;
M = (date.getMonth()+1 < 10 ? ‘0’+(date.getMonth()+1) : date.getMonth()+1) + ‘-’;
D = date.getDate() + ’ ';
h = date.getHours() + ‘:’;
m = date.getMinutes() + ‘:’;
s = date.getSeconds();
return Y+M+D+h+m+s;
}
(27)输出对象的属性
markers = {A:“1,2,3”,B:“3,4,5”};
for(var key in markers){
console.log( key )
}
(28)给数组添加新的属性
for(var i = 0; i<reData.data.length; i++){
reData.data[i][“index”] = i+1;
}
(29)将data.data的json对象里的precisionRate和strength属性提出放到arr数组里面
var obj={};
var subObj={};
var arr=[];
function HtmlRender(data){
var html="";
for(var i=0;i<data.data.length;i++){
var precisionRate=data.data[i].logFile.precisionRate;
var strength=data.data[i].logFile.strength;
subObj.precisionRate=precisionRate;
subObj.strength=strength;
obj.data=subObj;
arr.push(obj);
}
return arr;
}
(30):contains()选择器里是变量 :eq()选择器里是变量$(“ul li:eq(” + num + “)”)
var scoreOption = “liu”;
$("#stlist>p:contains(’"+scoreOption+"’)").addClass(“ex_green”);
$("#stlist>p:contains(’"+scoreAnswer+"’)").addClass(“st_select”);
(31)浏览器回退功能
返回上一步
(32)存取session
将对象存入session
var urlData ={};
urlData.classId = “1001”;
urlData.className = “lipen”;
urlData.createTime =“2018-06-28 15:33:02”;
sessionStorage.setItem(‘urlData’,JSON.stringify(urlData));
将变量存入session
var data_classId = “lemon”;
sessionStorage.setItem(‘data_classId’,data_classId);
从session中获取
var data_classId = sessionStorage.getItem(‘data_classId’);
var urlData = JSON.parse(sessionStorage.getItem(“info”));
(33) 获取当前页面的url?后面的参数
方法一:function GetRequest() {
var url = location.search; //获取url中"?“符后的字串
var theRequest = new Object();
if (url.indexOf(”?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
//跳转到指定tab块
var urlData = GetRequest();
var currentTitleType = -1;
if(urlData.studentId != null){
console.log(“直接跳转个人 标签页”);
$(".st_title #personal").addClass(‘redbg’).siblings().removeClass(‘redbg’);
$(’#labelpage .scmain_box’).show().siblings().hide();
if(currentTitleType == 1) { return; }//防止重复执行
currentTitleType = 1;
personalScore();
}else{
console.log(“直接跳转班级”);
if(currentTitleType == 0) { return; }
currentTitleType = 0;
classScore();
}
KaTeX parse error: Expected '}', got 'EOF' at end of input: …nction(){
if((this).html() == “个人”){
$(this).addClass(‘redbg’).siblings().removeClass(‘redbg’);
if(currentTitleType == 1) { return; }
currentTitleType = 1;
$(’#labelpage .scmain_box’).show().siblings().hide();
personalScore();
}else{
$(this).addClass(‘redbg’).siblings().removeClass(‘redbg’);
if(currentTitleType == 0) { return; }
currentTitleType = 0;
$(’#labelpage .sc_team’).show().siblings().hide();
classScore();
}
});
方法二://初始化URL参数
·//初始化URL参数
InitUrlParms = function () {
var args = new Object();
var query = location.search.substring(1);//获取查询串
var pairs = query.split("&");//在逗号处断开
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf(’=’);//查找name=value
if (pos == -1) continue;//如果没有找到就跳过
var argname = pairs[i].substring(0, pos);//提取name
var value = pairs[i].substring(pos + 1);//提取value
args[argname] = decodeURIComponent(value);//存为属性
}
return args;
};
var page_url = InitUrlParms();
//tab切换
$(’.tabs_box ul li’).click(function () {
var index = $(this).index();
$(this).addClass(‘active’).siblings().removeClass(‘active’);
$(’.news_content>div’).eq(index).show().siblings().hide();
});
//跳转到指定tab块
if (page_url[“studentId”] != null) {
var tabIndex = page_url[“studentId”];
} else {
var tabIndex = 0;
}
(34)JS格式化数字,每三位加逗号
function toThousands(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, ‘$1,’);
}
toThousands(1234567)===>“1,234,567”
(35)验证数字,大写字母,小写字母,特殊字符四选三组成的密码强度,且长度在8到30个数之间
表达式:
(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%&~()-+=]+$)(?![0-9\W_!@#$%^&*
~()-+=]+KaTeX parse error: Expected 'EOF', got '\W' at position 12: )[a-zA-Z0-9\̲W̲_!@#%^&~()-+=]{8,30}$ js写法: var regex = new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*
~()-+=]+)(?![a-z\W_!@#KaTeX parse error: Expected 'EOF', got '%' at position 1: %̲^&*`~()-+=]+)(?![0-9\W_!@#KaTeX parse error: Expected 'EOF', got '%' at position 1: %̲^&*`~()-+=]+)[a-zA-Z0-9\W_!@#KaTeX parse error: Expected 'EOF', got '%' at position 1: %̲^&*`~()-+=]{8,3…’);
if(!regex.test(pwd)){
msgError(“输入错误:密码不符合规则,请重新输入。”);
$("#password").focus();
return;
}
(36)返回顶部
KaTeX parse error: Expected '}', got 'EOF' at end of input: …nction(){
if((window).scrollTop() >= $(window).height()){
$(".comFixBtn02").css(“display”,“block”);
}else{
KaTeX parse error: Expected 'EOF', got '}' at position 43: …ay","none");
}̲
});
(37)//检查用…/;;
var flag=reg.test(a);
if(!flag){
//格式不正确
if(b.hasClass(“bankphone”)){
b.next(“span”).addClass(“cerActive”);
}
b.next(“span”).css(“display”,“block”);
b.next(“span”).html(“手机号格式不正确”);
b.next(“span”).removeClass(“right”);
}else{
//格式正确
if(b.hasClass(“bankphone”)){
b.next(“span”).removeClass(“cerActive”);
}
b.next(“span”).css(“display”,“none”);
b.next(“span”).html("");
}
}
}
//倒计时
function timeOut(a,b){
a.val(b+" S");
a.css({“background”:"#e2e2e2",“color”:"#999"});
var timer=setInterval(function(){
b–;
a.val(b+" S");
if(b<=0){
a.val(“重新获取”);
a.css({“background”:"#6baaf1",“color”:"#fff"});
clearInterval(timer);
a.removeAttr(“disabled”);
}
},1000);
}
//获取短信验证码
KaTeX parse error: Expected '}', got 'EOF' at end of input: …(){
if((this).attr(“disabled”)“disabled”){
alertD(“信息发送中,请耐心等待…”);
return;
}
var phoneNum=KaTeX parse error: Expected '}', got '用' at position 104: …
//用̲户中心
…(this));
}else{
//注册
var param={“check_username”:phoneNum.val()};
var param2={“phone”:phoneNum.val()};
if(phoneNum.val() && phoneNum.next(“span”).html()""){
issesUser(“data.php”,param,phoneNum,“data.php”,param2,$(this))
}else if(phoneNum.val()){
alertD(“请输入正确的手机号…”);
}else{
alertD(“请输入手机号…”);
}
}
});
(38)跨域 介绍:http://witmax.cn/easyxdm.html
(39)选中文本(利用Web API接口)
方法一:
jQuery.fn.selectText = function() {
var doc, element, range, selection;
doc = document;
element = this[0];
range = null;
selection = null;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
return range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
return selection.addRange(range);
}
};
如何使用:$("#text").selectText() //选中#text的文本
方法二:
/* 在一个HTML文档中选中所有加粗的文本。 */
var strongs = document.getElementsByTagName(“strong”);
var s = window.getSelection();
if(s.rangeCount > 0) s.removeAllRanges();
for(var i = 0; i < strongs.length; i++) {
var range = document.createRange();
range.selectNode(strongs[i]);
s.addRange(range);
}