JavaScript使用(笔记)

//当前点击的标签添加样式,同级别其他标签移除样式
$(this).addClass('hover').siblings().removeClass('hover');
//执行完改Ajax后执行下一步 同步
async:false
//{%$argv(0)%}(公司写法)获取页面传入的id
id="title_1"
var type = "{%$argv(0)%}";
 if (type != "") {
   $("#title_" + type + "").click();
 }
//默认点击第一个
$("#biao").eq(0).click();
//下载链接 href填路径  download填下载文件的名称
<a href="{*Doc}" download="{*Title}">
//获取该id下面最后一个span标签并隐藏
$("#hide span").last().hide();
//js生成随机数
function RndNum(n) {
var rnd = "";
for (var i = 0; i < n; i++)
rnd += Math.floor(Math.random() * 10);
return rnd;
}

RndNum(2);//表示2位数的随机数,以此类推
//一般处理程序方法生成随机数
/// <summary>
/// 随机生成验证码
/// </summary>
/// <param name="num">验证码长度</param>
/// <returns></returns>
public string GetCode(int num)
{
Random ran = new Random();
int[] arr = new int[num];
for (int i = 0; i < num; i++)
{
arr[i] = ran.Next(0, 9);
}
return string.Join("", arr);
}

string shu = GetCode(6);//生成随机数
//定义变量获取屏幕视口宽度
var windowWidth = $(window).width();
if (windowWidth < 640) {
    // do something
}
if (windowWidth >= 640) {
    // do something
}
//js判断一个字符在字符串出现的次数
var s='jhdoiweesdds';
var n=(s.split('d')).length-1;
alert(n);
//JSON转字符串格式
JSON.stringify(a)
//JSON转[[27, 4], [28, 1],]格式
var a = [];
var url = "apps/Traffic/effect.xmls";
var ajax = new xajax(url, "{%#root%}", "json");
var ret = ajax.execute("exes");
$.each(ret, function (index, item) {
    var b = [];
    b.push(item.Days)
    b.push(item.ct)
    a.push(b);
})
console.log(JSON.stringify(a));
//在js中判断如果字符串的长度大于10后面的就用省略号代替怎么实现?
var str="这里是字符串aaaa";//原始字符串
var s = str;//要展示的字符串
if(str.length>10){
    s=str.substring(0,10)+"...";
}
alert(s);
//html传id,js获取id
<a href="2.html?id=21">2</a>//页面1

//页面2
<script>
$(function () {
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]] = decodeURIComponent(strs[i].split("=")[1]);
}
}
var index_1 = theRequest['id'];
alert(index_1);
})
</script>
//生成GUID
function guid() {
    return 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
//读取cookie方法
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}
//设置cookie方法
function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}
//存cookie 1天后过期
setCookie('guids', guid, 1);

//读取cookie
var gid = getCookie('guids');
alert(gid);
//获取相差天数日期
function GetDateStr(AddDayCount) {
  var dd = new Date();
  dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期
  var d = dd.getDate();
  return y + "-" + m + "-" + d;
}

//昨日日期
var date = GetDateStr(-1);
alert(date);
$(function () {
   //同一个头部(frame),当前页面添加该样式 其余页面删除
   $('.active').removeClass('active');
   $(".cf li").eq(5).addClass("active");
})
 //回车键登录 
$(document).ready(function () {
  document.onkeydown = function (event) {
  if (event.keyCode == 13) //回车键的键值为13 
      submit();//登录方法
  };
});
//百分比计算 %
百分比=(当前执行数目/总数目)*100
//首个添加样式
$($(".shfw li")[0]).addClass('serc_tab_li');
//滚动条监听事件
$(document).ready(function () {//在文档加载完毕后执行
  $(window).scroll(function () {//开始监听滚动条
  //获取当前滚动条高度
  var topp = $(document).scrollTop();
   //用于调试 弹出当前滚动条高度
   alert(topp);
   //判断如果滚动条大于90则弹出 "ok"
   if (topp > 90) {
   //alert("ok");
  }
 })
})
//接近底部事件
 var end = 1;
    $(window).bind("scroll", function () {
        if ($(document).scrollTop() + $(window).height() > $(document).height() - 600 && end != 0)// 接近底部100px
        {
            end = 0;
           alert(1);
setTimeout(function () {
                end = 1;
            }, 1000)
        }
    });
//身份证号码自动空格.3+3+8+4
function FillIdentity(idValue) {
    return idValue.substring(0, 3) + " " + idValue.substring(3, 6) + " " + idValue.substring(6, 14) + " " + idValue.substring(14, 18);
}
//去除汉字
function RemoveChinese(strValue) {
    if (strValue != null && strValue != "") {
        var reg = /[\u4e00-\u9fa5]/g;
        return strValue.replace(reg, "");
    } else {
        return "";
    }
}
//sort从小到大排序  
var arr=["1","3","2"];  
arr.sort(sortNumber)
function sortNumber(a, b) {
    return a - b
}var nary = new Array("100", "100", "ff", "2222", "aa", "222");
alert(mm(nary));

//相同返回true,否则返回false
function mm(nary) {
    var istrue = false;
    for (var i = 0; i < nary.length - 1; i++) {
        if (nary[i] == nary[i + 1]) {
            istrue = true;
        }
    }
    return istrue;
}
item = "/Date(1544495323000)/";
var time = item.replace(/[^\d.]/g, "") * 1;//只保留数字      值为"1544495323000"      *1转为数字格式
alert(changeDate(time));
//日期时间戳转换
function changeDate(time) {
    var date = new Date(time);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    var hour = date.getHours().toString();
    var minutes = date.getMinutes().toString();
    var seconds = date.getSeconds().toString();
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + " " + hour + ":" + minutes + ":" + seconds;
}
//js 日期时间排序 数组
var timeArr=[
{'id':'A01','date':'2016-04-20 23:22:11'},
{'id':'A02','date':'2016-04-21 21:00:11'},
{'id':'A03','date':'2016-04-23 22:00:22'},
{'id':'A04','date':'2016-04-19 12:22:00'},
{'id':'A05','date':'2016-02-19 11:11:00'}
];

timeArr.sort(function(a,b) {
return Date.parse(b.date.replace(/-/g,"/"))-Date.parse(a.date.replace(/-/g,"/"));
});
 // 验证重复元素,有重复返回true;否则返回false
 function mm(arr) {
   var hash = {};
   for (var i in arr) {
     if (hash[arr[i]]) {
       return true;
     }
     // 不存在该元素,则赋值为true,可以赋任意值,相应的修改if判断条件即可
     hash[arr[i]] = true;
   }
   return false;
 }
//js关键词变色
SetKeywordColor("666");
//关键词变色 
function SetKeywordColor(value) {
    //创建正则表达式,g表示全局的,如果不用g,则查找到第一个就不会继续向下查找了;
    var regExp = new RegExp(value, "g");
    //遍历该样式下面的文字;
    $(".ser_data_tab").each(function () {
        var html = $(this).html();
        //将找到的关键字替换,加上highlight属性;
        var newHtml = html.replace(regExp, "<span style='color:#c90a16' >" + value + "</span>");
        //更新文章;
        $(this).html(newHtml);
    });
}
//js获取 and 选中 radio的值
<input type="radio" value="" name="rd" />
//获取radio选中的值
var rd = $("input[name='rd']").filter(":checked").val();
//设置radio选中值
$(":radio[name='rd'][value='值']").attr("checked", true);
//截取前三后三,中间五位*****号代替
var len= value.length;
var xx= value.substring(3,len-4);
var values = value.replace(xx,"*****");
//span数量加减
<input onclick="number('jian')" type="button" value="-" /> 
<span id="ss">1</span> 
<input onclick="number('jia')" type="button" value="+" /></p>

<script>
 function number(item) {
  var a = $("#ss").text();
  if (item == "jia") {
     a++;
  } else {
    if (a != 1) {
        a--;
     }
  }
  $("#ss").text(a);
}
</script>
//Ajax取模
<script>
    $(function () {
        var TypeId = "{%$argv(0)%}";
        var path = "{%#path%}";
        var url = path + "?xmls=xmls/product.xmls&method=pp&TypeId=" + TypeId;
        $.ajax({
            type: 'post',
            url: url,
            async: false,
            success: function (rets) {
                var json = JSON.parse(rets);
                var html = "";
                $.each(json, function (index, item) {
                    index ++;
                     html +="<div class=\"pull-left bad4-divs\"><a href=\"{~product-list/*ProductId}\" class=\"l2c-a\"><div class=\"l2ca-up bgcolof2\"><img src=\""+item.Pic+"\"></div><div class=\"l2ca-down bgcolof\"><p class=\"foz14 colo4 text-center\">" + item.ProductName + "</p></div></a></div>";
                     if (index % 4 == 0 || index == json.length) {
                         $("#bl").append("<li>" + html + "</li>");
                         html = "";
                     }
                    
                })

                $("#bl").append("<li>" + html + "</li>");
            }
        })

    })
</script>

 

posted @ 2018-06-25 17:03  时光博客  阅读(503)  评论(1编辑  收藏  举报