JavaScript&JQuery

8 篇文章 0 订阅

JavaScript & jQuery

debugger; //断点

jquery就是用JS写的,方便编程的一个方法集合 类库

页面高度

线上调试

调用别人的js 放下最下面,避免别人的服务器有问题

代码加密 :: 拿babel编译一遍,拿webpack打包一遍,再拿uglify压缩一遍,再拿eval加密一遍 --增加逆向难度(注意可能会降低性能)



Get_it_done

试试这个布局插件

JS合并数组的几种方法

document.write("<h1>这是一个标题</h1>");

关闭本身

window.close();
<input type="button" name="close" value="关闭" onclick="window.close();" />

页面高度说明

 if (!confirm("确定删除吗?")) return;

//离开时确认

window.onbeforeunload = function () { 一些自己的逻辑,但无法阻止关闭 return '590' }
function strIsEmpty(str){
    if (strings.replace(/(^s*)|(s*$)/g, "").length == 0) {
        return true;
    }
    return false;
}

*******************************************************************************************************************************

1. 初始化/创建

<script type="text/javascript">

    //ready 表示文档结构已经加载完成(不包含图片等非文字媒体文件) 只有JQ支持
    window.onload = function(){ //指示页面包含图片等文件在内的所有元素都加载完成。
        //初始化
        alert('hello world');
    }
    
    $(function () { 
        //初始化
        alert('hello world');
    })
    $().ready(function(){
        //初始化
        alert('hello world');
    })
    $(window).load(function(){ 
        //指示页面包含图片等文件在内的所有元素都加载完成。
        alert('see you again');
    })
    
</script>

*******************************************************************************************************************************

2. 引用

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.1.min.js"></script>

<script src="app1.js" defer>延迟加载(比较好)</script>
<script src="app2.js" async>异步加载</script>

动态引用

const jsObjer = document.createElement("script"); //动态创建JS
jsObjer.type = "text/javascript";
jsObjer.href = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.1.min.js";
document.head.appendChild(jsObjer); // 阻塞 默认异步

*******************************************************************************************************************************

对话框

1. 提示框

alert('欢迎!'); //提示框             ※~~

2. 对话框

if (confirm("你确定下单吗?")) {
    alert("点击了确定");
}
else {
    alert("点击了取消");
}

3. 文本输入框

var name = prompt("请输入您的名字", ""); //将输入的内容赋给变量 name, prompt(提示信息,默认值)
if (name)//如果返回的有内容  
{
    alert("欢迎您:" + name)
}

*******************************************************************************************************************************

浏览器用户返回上一步,自动刷新

onload = function () { alert('刷新了页面'); }
window.onpageshow = function (event) { if (event.persisted) { window.location.reload(); } };

*******************************************************************************************************************************

获取页面标签对象


JavaScript

var content = document.getElementById("content");
var x =document.getElementById("demo2")  // 根据ID找到元素
x.style.color="#ff0000";                // 改变样式
document.getElementById("demo").innerHTML="Hello JavaScript!"; //修改标签内html代码
var orderno = document.getElementById("order_no").value; //获取控件值 

$() 获取页面上的标签对象

$() jQuery的构造函数 也是css选择器、Xpath或html元素

样式属性示例
$(‘a’)页面中所有的<a>标签
$(“div>ul>a”)页面中所有的<div>中的<ul>子标签中的<a>子标签<div><ul><a></a></ul></div>
$(‘div a’)页面中所有的<div>中的<a>标签(子标签及或子子标签或…)<div><a></a><ul><a></a></ul></div>
$(’.aclass’)页面中所有 class=“aclass” 的标签<a class="aclass"></a>
$(’#aid’)页面中所有 id=“aid” 的标签<a id="aid"></a>
$(‘li[a]’)选择所有带有<a>子孙标签的<li>标签<li><a></a></li>
$(‘a[@title]’)选择所有带有 title 属性的<a>标签<a title="abcdefg"></a>
$(‘input[@name^=“mail”]’)name属性是以mail开头的input元素<input name="mailccc" type="text" value="0">
( ′ i n p u t [ @ n a m e ('input[@name (input[@name=“come”]’)name属性是以come结尾的input元素<input name="ccccome" type="text" value="0">
$(‘input[@name*=“abcd”]’)name属性包含abcd的input元素<input name="lucyabcdccc" type="text" value="0">
$(‘tr:not([th]):even’)<tr>元素的子孙中不含<th>的所有子孙的偶数项
$(‘a:first’)页面中所有的<a>标签的第一个标签
$(‘a:last’)页面中所有的<a>标签的最后一个标签
$(“ul li”).eq(n)<ul>中的第n个<li>标签

//①方式举例:
$(“input[name=‘newsletter’]”).attr(“checked”, true);
//表示 查找所有 name 属性是 newsletter 的 input 元素,并设置为选中状态
//②方式
$(“input[name!=‘newsletter’]”).attr(“checked”, true);
//查找所有 name 属性不是 newsletter 的 input 元素,并设置为选中状态
//③方式
$(“input[name^=‘news’]”).attr(“checked”, true);
//查找所有 name 以 ‘news’ 开始的 input 元素,并设置为选中状态
//④方式
( " i n p u t [ n a m e ("input[name ("input[name=‘letter’]").attr(“checked”, true);
//查找所有 name 以 ‘letter’ 结尾的 input 元素,并设置为选中状态
//⑤方式
$(“input[name*=‘news’]”).attr(“checked”, true);
//查找所有 name 包含 ‘man’ 的 input 元素,并设置为选中状态
// 根据上面的列举,需要的应该是②方式。
// 然而,这5种方式是比较容易混淆


获取子节点
$(this).find('span.demo') //子节点+子子节点+...
$(this).children('span.demo')  //子节点

兄弟节点
$(this).siblings('input') //获得 兄弟节点 'input'标签
$('td:contains("Henry")').prev()——内容包含有"Henry"<td>的上一个节点 
$('td:contains("Henry")').next()——内容包含有"Henry"<td>的下一个节点 
$('td:contains("Henry")').siblings()——内容包含有"Henry"<td>的所有兄弟节点 

父节点
$('th').parent() //父节点
$('#item1').parent().parent('.parent1'); //id=item1的父父节点(类为parent1)
$('li:parent');  //li的父节点
$('#items').parents('.parent1'); //parents()先检查父元素是否匹配,如果不匹配则一层一层往上找,直到找到匹配选择器的元素。如果什么都没找到则返回一个空的jQuery对象。
$('#items1').closest('.parent1'); //closest()会首先检查当前元素是否匹配,如果匹配则直接返回元素本身。如果不匹配则向上查找父元素,一层一层往上,直到找到匹配选择器的元素。如果什么都没找到则返回一个空的jQuery对象。

节点 增加&移除
$("<div><p>Hello</p></div>").appendTo("body"); 
//$()中的是一个字符串,用这样一段字串构建了jQuery对象,然后向<body/>中添加这一字串。

//在每个 p 元素结尾插入内容:(内)
$("p").append(" <b>Hello world!</b>");
$("<b>Hello World!</b>").appendTo("p");

//在每个 p 元素之后插入内容:(外)
$("p").after("<p>Hello world!</p>");    

//在每个 p 元素之前插入内容:(外)
$("p").before("<p>Hello world!</p>");

//移除所有 <p> 元素:
$("p").remove();

节点数组
$('.aclass'); //页面中所有 class="aclass" 的标签
$('.aclass').get(0); //也可缩写成
$('.aclass')[0]   //页面中所有 class="aclass" 的标签 的 第一个元素

标签对象内容
//获取标签属性
$(this).attr("data-abc") //获得节点的"data-abc"属性值 
//设置标签属性值
$(this).attr("data-abc","123") //设置节点的"data-abc"属性值为"123"
//移除标签属性
$(this).removeAttr("data-abc);


//获取标签内容
var value_int = parseInt($("#233").text());
$("#233").val() //表单内容
//设置标签内容
$("#233").text(value_int);
$("#233").html("<b>Hello world!</b>");
$("#233").val("590") //设置表单内容

//类
$("#233").addClass('current');
$("#233").removeClass('current');

*******************************************************************************************************************************

对象

var obj = {name:"小屁孩",age:17,interest:["睡觉","王者荣耀"]}; 
console.log(map['name']);//结果是小屁孩.
obj["height"] = 156.5;
obj["Fear"] = ['老鼠','鬼故事'];
obj.interest.push("吃货");

//遍历obj的所有子对象
for(var prop in obj){
    if(obj.hasOwnProperty(prop)){
        console.log('key is ' + prop +' and value is' + obj[prop]);
    }
}

if(typeof(obj) == "undefined" || obj == null){
    console.log('空的');
}
else console.log('不是空的');

*******************************************************************************************************************************

跳转

<a href="javascript:location.reload()">刷新</a> //刷新按钮
<a class="right-btn" href="Javascript:window.history.back()">返回</a>
window.location.reload();    //刷新  
window.location.replace("www.baidu.com");    //跳转
window.history.go(1);         //前进  
window.history.go(-1);        //返回+刷新  
window.history.forward();  //前进  
window.history.back();       //返回 
window.location.href = 'www.baidu.com';

*******************************************************************************************************************************

事件&函数


单击事件

$("a").click(function(){...}) 

移除所有 a 元素的事件处理器:

$("a").unbind();

遍历

$("li").each(function(i){ //遍历所有的<li>标签
    alert($(this).text())
    //return false; //停止遍历
});


*******************************************************************************************************************************

动画

http://www.w3school.com.cn/jquery/jquery_animate.asp

$("div").animate({left:'250px'});

$("div").animate({left:'250px', opacity: '0.8'}, 1000, function(){
    $("div").remove();
});

*******************************************************************************************************************************

焦点

$('#box1').focus();   //设置焦点
$('目标').blur();   //移除焦点

*******************************************************************************************************************************

Cookie

http://www.jb51.net/article/64330.htm

//设置cookie 其实就是这样:  document.cookie="name="+username;

//设置 Cookie
function setCookie(name, value) {
    var Minute = 1; //一分钟后过期
    var exp = new Date();
    exp.setTime(exp.getTime() + Minute * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
//expires 过期参数

//获取 Cookie
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

//删除 Cookie
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

*******************************************************************************************************************************

iframe


在 iframe 中调用 父窗体 的方法

//window.parent == 父窗体
window.parent.需要调用的方法();

在 父窗体 中调用 iframe 的方法

<iframe name="myFrame" src="child.html"></iframe> 
myFrame.window.functionName();

在 iframe 中调用另一个 iframe 的方法

window.parent.document.getElementById('iframe2_ID').contentWindow.需要调用的方法();


*******************************************************************************************************************************

ASP

Response.Write("<script> alert('请先查询'); </script>"); //有时候会破坏布局,用下面那种方法就好了
Page.ClientScript.RegisterStartupScript(this.GetType(),"message","<script>alert('保存成功');</script>");
Response.Redirect("www.baidu.com");
Response.End();

asp控件ID调用JS方法方法 控件ID.Attributes.Add(“事件OnCheckedChanged”, “JS事件()”);

例如:

html:

<asp:CheckBox ID="cbIsOnline" runat="server" />

cs:

cbIsOnline.Attributes.Add("OnCheckedChanged", "isShowSinceF()");

js:

function isShowSinceF() {
    if (document.getElementById("cbIsOnline").checked) {
        document.getElementById("cbIsOnline").checked = false;
    }
}


*******************************************************************************************************************************

获取地理位置 GetLocation

当前互联网地图的坐标系现状

地球坐标 (WGS84)

国际标准,从专业GPS 设备中取出的数据的坐标系
国际地图提供商使用的坐标系

火星坐标 (GCJ-02)也叫国测局坐标系

中国标准,从国行移动设备中定位获取的坐标数据使用这个坐标系
国家规定: 国内出版的各种地图系统(包括电子形式),必须至少采用GCJ-02对地理位置进行首次加密。

百度坐标 (BD-09)

百度标准,百度 SDK,百度地图,Geocoding 使用
(本来就乱了,百度又在火星坐标上来个二次加密)

开发过程需要注意的事

从设备获取经纬度(GPS)坐标

如果使用的是百度sdk那么可以获得百度坐标(bd09)或者火星坐标(GCJ02),默认是bd09
如果使用的是ios的原生定位库,那么获得的坐标是WGS84
如果使用的是高德sdk,那么获取的坐标是GCJ02

互联网在线地图使用的坐标系

火星坐标系:
iOS 地图(其实是高德)
Gogole地图
搜搜、阿里云、高德地图
百度坐标系:
当然只有百度地图
WGS84坐标系:
国际标准,谷歌国外地图、osm地图等国外的地图一般都是这个

//<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=BrDh9oBa5vSeG201dZR4u7IR5dkjE0UN"></script>
//百度坐标转高德火星坐标http://restapi.amap.com/v3/assistant/coordinate/convert?key=05d432016f0445aef264eb14303e1a91&locations=113.32094026382,23.122569837067&coordsys=baidu

function getLocationBaidu() {
    // 百度地图API功能
    // http://lbsyun.baidu.com/index.php?title=jspopular
    // http://developer.baidu.com/map/jsdemo.htm#i8_1
    var map = new BMap.Map("allmap");
    var point = new BMap.Point(116.331398, 39.897445);
    map.centerAndZoom(point, 12);

    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            map.panTo(r.point);
            //alert('您的位置:' + r.point.lng + ',' + r.point.lat);
            return r.point;
        }
        else {
            //alert('failed' + this.getStatus());
            switch (this.getStatus()) {
                case BMAP_STATUS_UNKNOWN_LOCATION:
                    alert("获取位置信息失败!位置结果未知");
                    break;
                case BMAP_STATUS_UNKNOWN_ROUTE:
                    alert("获取位置信息失败!导航结果未知");
                    break;
                case BMAP_STATUS_INVALID_KEY:
                    alert("获取位置信息失败!非法密钥");
                    break;
                case BMAP_STATUS_INVALID_REQUEST:
                    alert("获取位置信息失败!非法请求");
                    break;
                case BMAP_STATUS_PERMISSION_DENIED:
                    alert("获取位置信息失败!没有权限");
                    break;
                case BMAP_STATUS_SERVICE_UNAVAILABLE:
                    alert("获取位置信息失败!服务不可用");
                    break;
                case BMAP_STATUS_TIMEOUT:
                    alert("获取位置信息失败!超时");
                    break;
            }
        }
    }, { enableHighAccuracy: true })
}


function getLocation() {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 1000
    }
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, onError, options);
    }
    else {
        alert("该浏览器不支持获取地理位置");
    }
}

function showPosition(position) {
    //alert("纬度: " + position.coords.latitude + "  经度: " + position.coords.longitude);
    return { lat: position.coords.latitude, lon: position.coords.longitude };
    //window.location.href = Jump_Url + "&lat=" + position.coords.latitude + "&lon=" + position.coords.longitude;
}

//失败时
function onError(error) {
    switch (error.code) {
        case 1:
            alert("位置服务被拒绝");
            break;
        case 2:
            alert("暂时获取不到位置信息");
            break;
        case 3:
            alert("获取信息超时");
            break;
        case 4:
            alert("未知错误");
            break;
    }
}

*******************************************************************************************************************************

其它

html 子元素不触发父元素事件

1. 子元素事件中增加 event 如:<i οnclick="abc(event,123);">
2. 子元素事件中增加 ev.stopPropagation(); 如:function abc(ev,id){ev.stopPropagation();}
3. this也可以(代替event)

小数 取两位

四舍五入
var num =2.446242342;
num = num.toFixed(2); // 输出结果为 2.45
不四舍五入
1. Math.floor(15.7784514000 * 100) / 100
2. Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))

打印

window.print(); //打印当前页面
打印指定内容
//打印指定内容 可能会被浏览器屏蔽 解决:用户操作,比如按钮触发函数
var oWin = window.open("", "_blank");
oWin.document.write(document.getElementById("content").innerHTML);
oWin.focus();
oWin.document.close();
oWin.print();
oWin.close();

获取 RadioButtonList 的选中值

//获取 RadioButtonList 的选中值
var vRbtid = document.getElementById("radType");
var vRbtidList = vRbtid.getElementsByTagName("INPUT");//得到所有radio
for (var i = 0; i < vRbtidList.length; i++) {
    if (vRbtidList[i].checked) {
        var value = vRbtidList[i].value;
        console.log("RadioButtonList 的选中值为" + value);
    }
}

判断 Android 或 iOS 的多种方法

http://www.jb51.net/article/117472.htm

if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
  //alert(navigator.userAgent); 
  window.location.href ="iPhone.html";
} else if (/(Android)/i.test(navigator.userAgent)) {  //判断Android
  //alert(navigator.userAgent); 
  window.location.href ="Android.html";
} else { //pc
  window.location.href ="pc.html";
};

url编码

https://www.cnblogs.com/z-one/p/6542955.html
escape 和 unescape (对除ASCII字母、数字、标点符号 @ * _ + - . / 以外的其他字符进行编码。)
escape(‘http://www.baidu.com?name=zhang@xiao@jie&order=1’)
结果:“http%3A//www.baidu.com%3Fname%3Dzhang@xiao@jie%26order%3D1”
escape(‘张’)
结果:"%u5F20"


键盘事件

<input type="text" name="search" id="search" placeholder="输入关键词搜索" onkeydown="keySend(event);"  />
function keySend(event) {
	if (event.ctrlKey && event.keyCode == 13) { //回车键
		message();
	}
}

定时器

//定时器
var t = self.setInterval("clock()",1000); //i定时器id 每隔1000毫秒执行一次clock()
window.clearInterval(t); //取消对应的定时器

//等待器
var d = setTimeout("clock()",1000);  //一秒后执行一次clock()
clearTimeout(d); //取消对应的等待器

时间

var myDate = new Date();
myDate.getYear();        //获取当前年份(2位)
myDate.getFullYear();    //获取完整的年份(4位,1970-????)
myDate.getMonth();       //获取当前月份(0-11,0代表1月)
myDate.getDate();        //获取当前日(1-31)
myDate.getDay();         //获取当前星期X(0-6,0代表星期天)
myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours();       //获取当前小时数(0-23)
myDate.getMinutes();     //获取当前分钟数(0-59)
myDate.getSeconds();     //获取当前秒数(0-59)
myDate.getMilliseconds();    //获取当前毫秒数(0-999)
myDate.toLocaleDateString();     //获取当前日期
var mytime=myDate.toLocaleTimeString();     //获取当前时间
myDate.toLocaleString();        //获取日期与时间 日期时间脚本库方法列表
Date.prototype.isLeapYear 判断闰年
Date.prototype.Format 日期格式化
Date.prototype.DateAdd 日期计算
Date.prototype.DateDiff 比较日期差
Date.prototype.toString 日期转字符串
Date.prototype.toArray 日期分割为数组
Date.prototype.DatePart 取日期的部分信息
Date.prototype.MaxDayOfDate 取日期所在月的最大天数
Date.prototype.WeekNumOfYear 判断日期所在年的第几周
StringToDate 字符串转日期型
IsValidDate 验证日期有效性
CheckDateTime 完整日期时间检查
daysBetween 日期天数差

随机数

Math.random(); //生成[0,1)之间的一个随机数
Math.random() * 59520;    // [0,59520)


*******************************************************************************************************************************
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值