PHP 开发技术分享

WEB 开发中前端经常用到的 JS 片段(长期更新)

2020-07-25  本文已影响0人  phpworkerman

最近一年开发,因为团队规模较小,不光是开发后端,前端也要撸起袖子干,很多页面里需要 JS 操作的地方都要 google, 开发效率比较低,想着汇总一份常用的 JS 片段,以后工作也好查找。


判断页面里元素是否存在

# JS写法,不存在返回 null
document.getElementById('tag')
# jQuery写法,元素长度等于0表示不存在
$('#tag').length

获取或设置 input 值

# JS写法
word = document.getElementById('word');
word.value //取值
word.value = 'new word'; //赋值
# jQuery写法
$('#word').val() //取值
$('#word).val('field word'); //赋值

判断复选框是否选中

# JS写法
let word = document.getElementById('word');
word.checked  #选中返回 true , 没选中返回 false
# jQuery写法
$('#word').is(':checked'); #选中返回 true , 没选中返回 false
$('#word').prop('checked'); #选中返回 true , 没选中返回 false

获取 select 值

<select class="select-item" id="select-box">
    <option value="val-1">one</option>
    <option value="val-2" selected>two</option>
    <option value="val-3">three</option>
    <option value="val-4">four</option>
</select>
# JS写法
let select_item = document.getElementById('item'); #获取JS对象
let select_idx = select_item.selectedIndex; #获取选中索引
select_item.options[select_idx].value #值
select_item.options[select_idx].text #文本
# jQuery写法
$('.select-item').find('option:selected').val(); #select选中值
$('.select-item').find('option:selected').text(); #select选中文本
# zepto写法
$('.select-item option').not(function(){return !this.selected});

处理浮点数

Math.ceil(23.45); #向上取整,输出24
Math.floor(23.45); #向下取整,输出23
Math.round(23.45); #四舍五入,输出23

字符串替换

str.replace('$',' '); # $替换成成空字符串

倒计时

function countdown(strTime) {
        if(strTime < 0){
            $('.container .time-out').hide();
            return false;
        }

        let d = Math.floor(strTime / 86400);
        d = d >=10 ? d : '0' + d;
        let h = strTime - d * 86400;
        h = Math.floor(h / 3600);
        h = h >= 10 ? h : '0' + h;
        let m = Math.floor(strTime / 60 % 60);
        m = m >= 10 ? m : '0' + m;
        let s = Math.floor(strTime % 60);
        s = s >= 10 ? s : '0' + s;

        $('.day').text(d);
        $('.hours').text(h);
        $('.minute').text(m);
        $('.seconds').text(s);

        setTimeout(function(){
            countdown(strTime - 1);
        }, 1000);
    }

原生JS使用Ajax

var xhr = new XMLHttpRequest();

上一篇 下一篇

猜你喜欢

热点阅读