JavaScript和Jquery个人笔记

前言

记录一下我写JavaScript和Jquery的时候遇到的一些事

价格 * 数量 = 金额

这个例子算是告诉我了,不要在HTML上写什么onchange方法,直接在Jquery里面写

function ChechUpPrice(value, index) {
    var UnitPrice = $("#UnitPrice").val();
    $("#TotalAmount[" + index + "]").val((UnitPrice * value).toFixed(3) + 'RMB');
}
    $('#UnitPrice,.wareQty').change(function () {
        var unitPrice = $('#UnitPrice').val();
        if (unitPrice && parseFloat(unitPrice) > 0) {
            unitPrice = parseFloat(unitPrice);
        } else {
            unitPrice = 0;
        }
        $('.wareQty').each(function (i,e) {
            var id = $(e).attr('stockWareId');
            var quantity = $(e).val();
            if (quantity && parseFloat(quantity) > 0) {
                quantity = parseFloat(quantity);
            } else {
                quantity = 0;
            }
            $('#totalAmount' + id).text(parseFloat(quantity * unitPrice));
        });
    })
  <span id="totalAmount@(item.ProductStockWarehouseId)"></span>

js计算时间差值

var d1 = new Date('2016/03/28 10:17:22');
var d2 = new Date('2016/03/28 11:17:22');
console.log(parseInt(d2 - d1));//两个时间相差的毫秒数
console.log(parseInt(d2 - d1) / 1000);//两个时间相差的秒数
console.log(parseInt(d2 - d1) / 1000 / 60);//两个时间相差的分钟数
console.log(parseInt(d2 - d1) / 1000 / 60);//两个时间相差的小时数

如果,拿到的不是日期类型,而是"2016-03-28 10:27:00"这种的字符串格式呢,那么就需要先将字符串转换为日期类型。

var t1 = "2016-03-28 10:27:00";
var d1 = t1.replace(/\-/g, "/");
var date1 = new Date(d1);

判断敲回车或Shift+回车

敲回车的时候,还要判断shift键没有按下,否则失效

   <input type="text" id="test" value="" />
    <script>
     $(function(){
         $('#test').keydown(function (e){
             if(e.keyCode == 13 && !e.shiftKey){
                 console.log('我敲了回车')
             }else if(e.shiftKey && e.keyCode == 13 ){
                console.log('我敲了Shift+回车')
             }
         })
     })
    </script>

js控制textarea换行

有时候,在做聊天的时候,textarea我希望敲回车发送消息,敲shift+回车才是换行,这个和上面的一样的其实

因为本身textarea就有敲回车换行的功能,所以我们只需要禁止敲回车换行即可

   <textarea id="test" style="height: 600px; width:600px;" >大家好,我是Vae</textarea>


    <script>
     
     $(function(){
         $('#test').keydown(function (e){
             if(e.keyCode == 13 && !e.shiftKey){
                 console.log('我敲了回车')
                 e.preventDefault();
             }
         })
     })
            
    </script>

就是如此preventDefault是禁止事件发生的意思,这样敲回车就不会换行了,按下shift+回车才会换行

$(this)选择当前元素

我现在有4个a标签的按钮,我想点击谁,谁的名字就输出,如下

可以使用$(this)实现,代码如下

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title Page</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>


            <ul id="divGuestList" class="btn-group btn-group-justified btn-group-xs"></ul>
                <li>
                    <a href="#" onclick="test($(this))" class="btn btn-primary">Apple</a>
                    <a href="#" onclick="test($(this))" class="btn btn-primary">Samsung</a>
                </li>
                <li>
                    <a href="#" onclick="test($(this))" class="btn btn-primary">Vae</a>
                    <a href="#" onclick="test($(this))" class="btn btn-primary">xusong</a>
                </li>
            </ul>

    <script>
        function test($this){
            console.log($this.html())
        }
    </script>
</body>
</html>

可以看到,HTML元素写的是$(this),下面的js方法写的就是$this.没有括号了

结果如图所示:

前端调试禁止其他js

在Chrome调试前端的js的时候,总是会进入到相关的js,比如Jquery.js

真的是神烦的,一进去就死命的在里面,出不来的,这个时候直接把Jquery.js关进黑盒就不会再进入调试了,直接在js上右键,选择BlackBox

js添加a标签href属性和文本

//html元素
<a id="UrlReferrer" href="" target="_blank"></a>

//js代码
document.getElementById("UrlReferrer").href = GuestList[nRet].guest_urlReferrer;                         document.getElementById("UrlReferrer").innerText = "点击查看"

js控制浏览器标签页文本闪烁提醒 (已弃用,采用下面的Push.js)

var titleInit = document.title,
    isShine = false;
window.onfocus = function () {
    isShine = false;
};

isShine = true;
setInterval(function () {
    var title = document.title;
    if (isShine == true) {
        if (/新/.test(title) == false) { //这个是正则test方法
            document.title = '【新消息】';
        } else {
            document.title = '【请查看】';
        }
    } else {
        document.title = titleInit;
    }
}, 500);

Push.js推送通知

最近做一个网页聊天提醒的功能,我尝试了浏览器标题栏变换字体,但是还是不行,打开的窗口一多根本注意不到,所以使用Push.js推送通知

首先下载js

npm install push.js --save

然后看html

<body>
    <script src="push.min.js"></script>

    <a id="demo_button" href="#" class="button">View Demo</a>
    <!-- Push.Permission.request(); -->
    <script>

        function demo() {
            Push.create('提示', {
                body: '有客户与您聊天',
                timeout: 4000,
                onClick: function () {
                    window.focus();
                    this.close();
                },
                vibrate: [200, 100, 200, 100, 200, 100, 200]
            });
        }

        $(document).ready(function () {
            $("#demo_button").click(demo);
        });

    </script>
</body>

:我不知道本地是无法弹窗通知的,在VS Code里面本地打开html,一直刷新啊刷新啊,死都不出来弹窗,最后换成服务器模式,可以了.......

调试js

某个页面自己的js可以在浏览器上直接打断点调试,但是如果这个页面用了其他页面,其他页面的js调试办法很简单,写一个debugger即可

debugger

a标签空跳转

 <a href="javascript:;"></a>

Jquery操作属性,读取,赋值,添加,判断

//循环遍历divGuestList这个元素下所有的li下的a元素
$("#divGuestList li a").each(function () { 
    //判断class属性里面有没有某个值
    if ($(this).hasClass(info.CustomerId)) {
        //获取id的值
        $(this).attr('id')
        //修改属性id的值
        $(this).attr({id:'vae'})
        //class属性添加一个内容
        $(this).addClass("btn-yellow");
    }
});

链式

这个选中元素下的元素还可以使用$(this).find('a')来表示,感觉像是爬虫似的

siblings()的意思就是所有的同级元素,使用超级方便了

<script type="text/javascript">
    $(function () {
    $('.list-tittle-panel li').mouseenter(function () {
        $(this).css({ "background-color": "#1b4684"});
        $(this).find('a').css({ "color": "#ffffff" });
    });
    $('.list-tittle-panel li').mouseleave(function () {
        $(this).css({ "background-color": "#f0f0f0"});
        $(this).find('a').css({ "color": "#666" });
    });
    $('.list-tittle-panel li').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
    });

    $('.classification li').click(function () {
        $(this).css({ "color": "#0cb0b7" }).siblings().css({"color": "#666" });
        $(this).addClass('active').siblings().removeClass('active');
    });      
});
</script>

还有,上面的鼠标进入,移出事件还是不好,直接用hover,完美

$('.list-tittle-panel li').hover(function () {
    $(this).css({ "background-color": "#1b4684"});
    $(this).find('a').css({ "color": "#ffffff" });
}, function () {
    $(this).css({ "background-color": "#f0f0f0"});
    $(this).find('a').css({ "color": "#666" });
});

标签页

讲讲标签页是怎么实现的,参考Bootstrap就可以理解了,但是我不希望使用Bootstrap,我们可以自己写

首先标签页就是下面这东西

我们可以先写一个ul和li作为标签页的选择,然后内容呢,我们可以写div,ul+li或者单纯的p元素

三个标签页就写3个内容元素,我点击第一个标签页就显示第一个内容元素,其他两个隐藏

思路大概就是这样,看一下js怎么控制

首先标签页的点击去除了on,又给我点击的那个加了on,这个on在css里面有样式,点了之后就好看了

index这个是获取下标的,看你点击的是第几个,然后通过下标找到内容元素,这个eq方法之前没用过,可以通过下标获取元素

然后自己加上显示的class,其他的内容元素移除显示class

在css里面控制显示class,display设置为block还是flex看情况

$(function () {
    $('.product-cates li').click(function () {
        $(".product-cates li").removeClass('on');
        $(this).addClass('on');
        var index = $(".product-cates li").index($(".product-cates li.on"));
        var currUrl = $(".product-list").eq(index);
        currUrl.addClass('hotshow');
        currUrl.siblings(".product-list").removeClass('hotshow');
    });
});

多个CheckBox被选中,条件筛选

多个ul和li,每一个ul有一个name,记录是哪个条件

然后选完条件传参的时候我脑残的写了好几个if elseif....

凡是写了很多if的,都是可以被优化的

//被选中的所有的CheckBox
$("input:checkbox:checked").each(function () {
    //判断被选中的这个CheckBox的name是啥,是哪个条件列里面的
    if ($(this).attr('name') == 'vae') {
        //获取值
        $(this).val()

我是这样做的,结果以string形式传,然后我的数据返回之后是动态拼接到tbody的,清空tbody是这样

$('tbody').html('');

当前url解码,截取,替换,多class

//获取当前url,unescape是解码的,因为有时候url里面有%27这种单引号
var url = unescape(this.location.href);
//截取
ab=url.substring(url.indexOf('vae')+7, url.indexOf('.html'))
//替换单引号
aaa.replace(/\'/g, '')
//不存在
$('.list li').not('.active').hover(function () {...
//找到a
$(this).find('a').css({ "color": "#666" });
$(this).css({ "background-color": "#f0f0f0" });
//两个class,且关系,看到没是加逗号
$('.list,.li')                                                               

select下拉选择框赋不上值

这个问题搞了我半天,我给一个select赋值没效果

$('#MemoryCategoryId_2').val(0);

原因是因为这个select没有给它加上option,加一个默认的就可以了

<select id="mm" name="mm">
    <option value="0">未选择</option>
</select>

页面滚动检测

有一个侧边的导航,点击之后,有锚点调到页面相应的位置,现在需要滚动页面的时候,侧边导航也跟着变化

        $(window).scroll(function () {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (scrollTop < 600) {
                $('.technology-navigation-bar li:nth-child(1)').addClass('active').siblings().removeClass('active');
            }
            else if (scrollTop >= 600 && scrollTop < 1000) {
                $('.technology-navigation-bar li:nth-child(2)').addClass('active').siblings().removeClass('active');
            }
            else if (scrollTop >= 1000 && scrollTop < 1600) {
                $('.technology-navigation-bar li:nth-child(3)').addClass('active').siblings().removeClass('active');
            }
            else if (scrollTop >= 1600  && scrollTop < 2290) {
                $('.technology-navigation-bar li:nth-child(4)').addClass('active').siblings().removeClass('active');
            }
            else if (scrollTop >= 2290) {
                $('.technology-navigation-bar li:nth-child(5)').addClass('active').siblings().removeClass('active');
            }
        })

jquery的offset() 距离浏览器顶部的距离

还是侧边导航的问题,我要距离页面的顶部有一定的距离,不能被顶上去

if ($(".technology-navigation-bar").offset().top < 300) {
    $(".technology-navigation-bar").offset({top:300});
}

拿到url的值

    ViewBag.time = Request.QueryString["time"] ?? "";
    ViewBag.sort = Request.QueryString["sort"] ?? "";

这样拿到值之后,赋值给隐藏的input,然后在js里面调用
根据url的值更改我的HTML里面的active状态

  $(".essearch-tab li:eq(" + $('#type').val() + ")").addClass("active").siblings().removeClass("active");
posted @ 2019-07-03 11:18  蜀云泉  阅读(252)  评论(0编辑  收藏  举报