前端实用笔记

3/3/2022 ESx

# 前端实用笔记🔎

# 常规🍳

# 1、获取地址栏参数

function getRequest() {
	var url = window.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]]=decodeURI(strs[i].split("=")[1]);?
    }
}
return theRequest;
}
var username= getRequest().username;
1
2
3
4
5
6
7
8
9
10
11
12
13

# 1.2、获取地址栏参数

const getParameters = (URL) => {
  URL = JSON.parse(
    '{"' +
      decodeURI(URL.split("?")[1])
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
  return JSON.stringify(URL);
};
 
getParameters(window.location);
// Result: { search : "easy", page : 3 }

// 或者更为简单的:
Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }

//URLSearchParams兼容:https://caniuse.com/?search=URLSearchParams
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 2、SELECT获取option的值

var options=$("#clasname option:selected");
var classname = options.text();

<select onchange="getCgfs(this);"></select>
function getCgfs(obj) {
    cgfs = obj.options[obj.selectedIndex].value;
}

$("input[name='nrId']:checked").each(function(i){
   let nrId = +$(this).val();
});
1
2
3
4
5
6
7
8
9
10
11

# 3、含有多个条件的 if 语句

// bad
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
// good
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
1
2
3
4
5
6
7
8

# 4、对 Null、Undefined、Empty 这些值的检查

// bad
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// good
let test2 = test1 || '';
1
2
3
4
5
6

# 5、判断变量是否存在的缩写法

// bad
if (test1 === true) or if (test1 !== "") or if (test1 !== null)

// good 
//it will check empty string,null and undefined too
if (test1)
  
// 注意:当 test1 为任何值时,程序都会执行 if(test1){ } 内的逻辑,这种写法在判断 NULL 或 undefined 值时普遍使用。
1
2
3
4
5
6
7
8

# 6、switch 对应的缩写法

// bad
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// good
var data = {
  1: test1,
  2: test2,
  3: test
};

data[something] && data[something]();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 7、字符串转换为数字

//bad 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 
//good 
let test1 = +'123'; 
let test2 = +'12.3';
1
2
3
4
5
6

# 8、按位非和 indexOf 缩写法

//我们通常用到 indexOf() 方法在一个数组查找特定值
//bad
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}
//good
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

//对除 -1 外的任何数进行 按位非(~) 运算都会返回真值。把按位非的结果再次进行逻辑取反就是 !~,这非常简单。
// 或者我们也可以使用 includes() 函数:
if (arr.includes(item))
{ 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 9、前端上传图片并回显

<!-- 用于预览图片-->
<img class="img" src="">

<!-- 用于读取图片 -->
<input class="input-img" type="file" accept="image/*" style="display: none;">

<!-- 用于触发事件 -->
<button class="upload-btn">选择图片上传</button>
1
2
3
4
5
6
7
8
/*文件头像*/
$(".user_img_diy").click(function (){
    $('.input-img').click();
});
$('.input-img').on('change', function () {
    const file = $('.input-img').get(0).files[0];
    if (!file || file.length === 0) {
        return
    }
    const fileName = file.name;
    const fileType = fileName.substr(fileName.lastIndexOf(".")).toUpperCase();
    if (fileType !== ".GIF" && fileType !== ".PNG" && fileType !== ".JPG" && fileType !== ".JPEG") {
        alert('请选择图片文件!') // 提示
        return
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        alert('上传图片大小不能超过 2MB!') // 提示
        $('.input-img').get(0).value = ''
        return
    }

    const formdata = new FormData();
    formdata.append("avatarfile", file);
    // 上传头像
    $.ajax({
        url: url,
        data: formdata,
        type: "post",
        processData: false,
        contentType: false,
        success: function(result) {
           console.log(result);
           $('.user_img_diy').attr('src', "data:image/png;base64," +result.data)
        }
    })
})

/**
 * 文件流转为 base64
 * @param {*} file
 */
function fileToBase64(file) {
    const URL = window.URL || window.webkitURL;
    return URL.createObjectURL(file);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

# Ajax👓

# 1、传数组对象到后台

var list = [{a:x,b:v}];
$.ajax({
        url:'/save',
        type:'post',
        data:JSON.stringify(list),
        contentType:"application/json",
        success:function (obj)
        {
            
        },dataType:'json'
    })


//  后台
//  @PostMapping("save")
//  public AjaxResult saveRecordTemporaryService(@RequestBody List<Bean> list)
//  {
//    return AjaxResult.success();
//  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 2、传ID数组到后台

let chk_value = [1,2,3,4,5,6];
$.ajax({
    url:'/sheet/test',
    type:'post',
    data:{ids:chk_value},
    traditional:true,
    success:function (obj)
    {
        
    },dataType:'json'
});

// 后台接口
// @PostMapping("test")
// public AjaxResult downloadExcel(Integer[] ids) {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3、传组合对象

# 3.1、组合对象

@Data
public class AccountVO
{
    private AccountEntity accountEntity;

    private List<AccountProductEntity> accountProductEntityList;

    private List<AccountInvoiceEntity> accountInvoiceList;
}
1
2
3
4
5
6
7
8
9

# 3.2、前端代码

function saveCommon()
{
    const accountEntity = $("#kpForm").serializeJson();
    const accountEntityVO = {};
    accountEntityVO.accountEntity = accountEntity;
    let accountProductEntityList = [];
    accountProductEntitySet.forEach((el,index) => {
        accountProductEntityList.push(el);
    });
    accountEntityVO.accountProductEntityList = accountProductEntityList;
    let accountInvoiceList = [];
    accountInvoiceEntityMap.forEach((el,index) => {
        accountInvoiceList.push(el);
    });
    accountEntityVO.accountInvoiceList = accountInvoiceList;
    $.ajax({
        url:'/saving',
        type: 'post',
        data:JSON.stringify(accountEntityVO),
        contentType:"application/json",
        success:function (obj)
        {
        },dataType: 'json'
    })
}
$.fn.serializeJson=function(){
    var serializeObj={};
    var array=this.serializeArray();
    $(array).each(function(){

        if(serializeObj[this.name]){
            if($.isArray(serializeObj[this.name])){
                serializeObj[this.name].push(this.value);
            }else{
                serializeObj[this.name]=[serializeObj[this.name],this.value];
            }
        }else{
            serializeObj[this.name]=this.value;
        }
    });
    return serializeObj;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

# 3.3、后端接收

@PostMapping("saving")
public AjaxResult saveAccount(@RequestBody AccountVO accountEntityVO)
{}
1
2
3