前端日常问题记录

1、react执行webpack打包后打开html空白页问题
替换BrowserRouter为HashRouter

import { BrowserRouter as Router, Route, Redirect, Link, Switch } from "react-router-dom";
import { HashRouter as Router, Route, Redirect, Link, Switch } from "react-router-dom";

原因:

BrowserRouter是需要对服务器端进行配置的,因为不同的path默认会请求不同的服务器资源,HashRouter的话都是请求的index.html这个资源,所以不会有问题。npm run dev不会有问题,是因为你的node起的本地服务已经做好了这个转发配置

2、Safari不能正确解析yyyy-mm-dd

var date_format = "2016-06-10".split('-').join('/')
var deadline = new Date(date_format + " 23:59");

3、JS判断分秒为零时

let date_format = date && date.split('-').join('/')
const time = new Date(date_format);
const hour = time.getHours()
const min = time.getMinutes()
if (hour === 0 && min === 0) return true;
else return false;

4、JS比当前时间多一个小时

let now = new Date();
const nowAfterHours = new Date(now.getTime() + 60 * 60 * 1000);

5、JS时间分钟小于30调整为30,大于30小于60调整为60

let startTime = new Date(startdate);
let endTime = new Date(endTime);
if (endTime.getMinutes() < 30 && endTime.getMinutes() > 0) {
     endTime = new Date(endTime.getTime() + (30 - endTime.getMinutes()) * 60 * 1000);
} else if (endTime.getMinutes() > 30) {
    endTime = new Date(endTime.getTime() + (60 - endTime.getMinutes()) * 60 * 1000);
}

6、JS判断对象类型

typeof form.endate === "object"

7、字符串匹配关键字全部替换
如下替换href="//为href="http://

str.replace(new RegExp( "href=\"//" , "g" ), "href=\"http://")

8、前端根据手机设备调用原生方法

const browser = {
    versions: (function () {
        const u = navigator.userAgent,
            app = navigator.appVersion;

        return {
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
            android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, // android终端或者uc浏览器
            iPhone: u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1, // 是否为iPhone或者QQHD浏览器
            iPad: u.indexOf("iPad") > -1, // 是否iPad
            weChat: u.indexOf("MicroMessenger") > -1
        };
    })()
};
// 扫一扫
export function scan() {
    if (browser.versions.android) {
        window['WebViewJavascriptBridge'].callHandler("scan");
    } else if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
        window['webkit'].messageHandlers.scan.postMessage("");
    }
}

9、iOS及safari时间解析错误

function toDate(time:string,fmt?: string) {
    if (fmt == null) fmt = 'yyyy-MM-dd hh:mm:ss';

    const str = time.replace(/\T/g, ' ');
    // fmt为日期格式,str为日期字符串
    const reg = /([yMdhmsS]+)/g; // 日期格式中的字符
    let key = {}, conv = (v) => { let val = parseInt(v, 10); return isNaN(val) ? 0 : val; };
    const tmpkeys = fmt.match(reg);
    for (let i = 0; i < tmpkeys.length; i++) {
        key[tmpkeys[i].substr(0, 1)] = i + 1;
    }
    const r = str.match(fmt.replace(reg, "(\\d+)"));
    return new Date(conv(r[key["y"]]), conv(r[key["M"]]) - 1, conv(r[key["d"]]), conv(r[key["h"]]), conv(r[key["m"]]), conv(r[key["s"]]));
}

或者

export function getDate(date: string | Date, def?: Date): Date | undefined {
    return date instanceof Date
        ? date
        : date
        ? new Date(
              date
                  .replace(/\-/g, "/")
                  .replace(/T/g, " ")
                  .substr(0, 19)
          )
        : def;
}

10、获取两天后的时间或者N月后时间

/**
 * 获取指定日期N天后日期
 * @param days GetDateStr
 */
export function getSetDateStr(date: string, days: number, fmt: string = "yyyy-MM-dd") {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}
/**
 * 获取指定日期N月后日期
 * @param days GetDateStr
 */
let date = new Date();
date.setMonth(date.getMonth() + N)

11、js取消键盘响应

 $('.autoFocus').blur();

12、日历插件
插件地址

13、iconfont下载全部

在浏览器中按f12打开【开发人员工具】,找到【console(控制台)】,输入以下代码,再按回车,稍等片刻即可把全部图标加入购物车
var ll = document.getElementsByClassName('icon-gouwuche1'); for (var i=0; i

14、react路由跳转传参

this.goTo({
       pathname: `orderDetail`,
       state: this.roomData
})
//接收参数
this.props.location.state

goTo(path: string | LocationDescriptorObject, state?: any) {
        if (this.props.match && path) {
            let isString = typeof path === "string",
                paths = isString ? (path as string) : (path as LocationDescriptorObject).pathname;

            if (!PREFIX_REG.test(paths)) {
                const url = this.props.match.url;

                paths = `${url}${SUFFIX_REG.test(url) ? "" : "/"}${paths}`;

                isString ? (path = paths) : ((path as LocationDescriptorObject).pathname = paths);
            }
        }

        this.__goTo(path, state);
}

protected __goTo(path: string | LocationDescriptorObject, state?: any) {
        this.props.history && this.props.history.push(path as any, state);
}

15、js根据数组循环key值获取class类型,确保相邻值不同

randomClassValue(i) {
        let value = i % 4 ? i % 4 : 4
        return "back-" + value;
}

16、超出部分可以滚动

{this.renderLoading(this.props.state.showloading)} {this.renderFormData()}

17、获取本周开始结束时间及本周是第几周

this.BeginDate = getWeekDate("start");
this.EndDate = getWeekDate("end");
/** 获取本周开始结束时间 */
export function getWeekDate(data: any) {
    const now = new Date(); // 当前日期
    let nowDayOfWeek = now.getDay(); // 今天本周的第几天
    if (nowDayOfWeek === 0) nowDayOfWeek = 7;
    const nowDay = now.getDate(); // 当前日
    const nowMonth = now.getMonth(); // 当前月
    const nowYear = now.getFullYear(); // 当前年
    if (data === "start") return new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1).format("yyyy-MM-dd");
    else return new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek)).format("yyyy-MM-dd");
}
/** 获取本周是第几周 */
  getWeek(dt) {
    let d1 = new Date(dt);
    let d2 = new Date(dt);
    d2.setMonth(0);
    d2.setDate(1);
    let rq = d1 - d2;
    let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
    let num = Math.ceil(days / 7);
    console.log("num", num);
    return num;
  }

18、获取下一周或者获取上一周

addWeek(week: number) {
        this.BeginDate = getDate(this.BeginDate).dateAdd("w", week).format("yyyy-MM-dd");
        this.EndDate = getDate(this.EndDate).dateAdd("w", week).format("yyyy-MM-dd");
        const {tabIndex} = this.state as any;
        this.getData(null, tabIndex);
    }
// 第几周
getDate(date: string | Date): Date {
    return date instanceof Date
        ? date
        : date &&
        new Date(
            date
                .replace(/\-/g, "/")
                .replace(/T/g, " ")
                .substr(0, 19)
        );
}

19、react前端升级样式版本过高报错

const style = { style: { width: '100%', minWidth: '75px' } } as any;
}
                    >

20、数组遍历改变值,蚂蚁组件pick组件赋值

entrances = this.state.v5sflc ? this.state.v5sflc.map(c => ({ label: c.TagName, value: c })) : [];

21、react路由跳转重写

componentDidMount() {
        window['payGoTo'] = (path, state) => {
            this.path = state ? path : null;
            this.goTo(path);
        }
        this.props.getOrderDetailAction(this.props.match.params.id);
}
protected __goTo(path: string | LocationDescriptorObject, state?: any) {
        if (this.props.match.params.type === "submit") {
            this.props.history && this.props.history.push(path as any, state);
        } else if (this.path) {
            // alert(`${this.props.match.url}/${this.path}`)
            let index = `${this.props.match.url}}`.indexOf("resourcePayErr");
            let result = `${this.props.match.url}}`.substr(0, index);
            // alert(result)
            this.props.history && this.props.history.replace(`${result}${this.path}` as any, state);
            this.path = null;
        }
}

22、html获取base64串并与iOS交互




    
    html5实现上传
    


    
    
    


23、html生成iOS启动图方法
Contents.json

{
  "images" : [
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "2436h",
      "filename" : "[email protected]",
      "minimum-system-version" : "11.0",
      "orientation" : "portrait",
      "scale" : "3x"
    },
    {
      "orientation" : "landscape",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "minimum-system-version" : "11.0",
      "subtype" : "2436h",
      "scale" : "3x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "736h",
      "filename" : "[email protected]",
      "minimum-system-version" : "8.0",
      "orientation" : "portrait",
      "scale" : "3x"
    },
    {
      "orientation" : "landscape",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "minimum-system-version" : "8.0",
      "subtype" : "736h",
      "scale" : "3x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "667h",
      "filename" : "[email protected]",
      "minimum-system-version" : "8.0",
      "orientation" : "portrait",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "[email protected]",
      "extent" : "full-screen",
      "minimum-system-version" : "7.0",
      "scale" : "2x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "retina4",
      "filename" : "[email protected]",
      "minimum-system-version" : "7.0",
      "orientation" : "portrait",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "scale" : "1x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "[email protected]",
      "extent" : "full-screen",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "[email protected]",
      "extent" : "full-screen",
      "subtype" : "retina4",
      "scale" : "2x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}

生成启动图html代码:




    
    html5生成iOS启动图
    


选取图片生成指定尺寸图片
1、在picConfigure中配置图片名称和对应图片尺寸
2、选取图片后会自动生成并下载图片

改进版本



    
        
        html5生成iOS启动图
        
    
    
        
选取图片生成指定尺寸图片
1、在picConfigure中配置图片名称和对应图片尺寸
2、选取图片后会自动生成并下载图片

24、公司问题记录:
(1)报错Error: Cannot find module 'uglifyjs-webpack-plugin'

sudo cnpm i -S uglifyjs-webpack-plugin
// pure_getters: true,

(2)内部安装

npm config set registry http://192.168.1.247:86/npm/RECO.NPM/
cnpm config set registry http://192.168.1.247:86/npm/RECO.NPM/
yarn config set registry http://192.168.1.247:86/npm/RECO.NPM/

(3)报错

ERROR in [at-loader] ./node_modules/@types/react-transition-group/TransitionGroup.d.ts:16:45 
    TS2314: Generic type 'ReactElement

' requires 1 type argument(s). ERROR in [at-loader] ./node_modules/@types/react-dom/index.d.ts:90:18 TS2314: Generic type 'ReactElement

' requires 1 type argument(s).

版本匹配不上造成,对应位置加上标签

type TransitionGroupProps =
        (IntrinsicTransitionGroupProps & JSX.IntrinsicElements[T]) | (ComponentTransitionGroupProps) & {
        children?: ReactElement | Array>;
        childFactory?

(child: ReactElement

): ReactElement

; [prop: string]: any; };

( element: ReactElement

, container: Element | null, callback?: () => void ): Component | Element | void;

25、截取字符串中中文开头的字符
截取字符串如下

上海万象城国际都市综合体位于位于地铁10号线紫藤路站上盖,紧邻吴中路和外环高架内侧,由24万平方米万象城顶级购物中心,14万平方米超甲级写字楼集群,3万平方米国际精品酒店组成,总体量达53万平方米,是截止目前华润置地在上海大区最大的最高端的商业综合体项目
上海万象城国际都市综合体延续和超越了万象城产品线的卓越品质,在每个业态上都有所创新和突破。

上海万象城国际都市综合体位于上海“西大门”虹桥区域,处于虹桥涉外贸易中心、虹桥临空经济园区、七宝生态商务区、南方商城商务区、漕河泾商务区的中间位置,尽占大虹桥CBD核心区位优势。距虹桥综合交通枢纽仅2千米,一小时辐射繁荣的长三角经济圈。

上海万象城购物中心总体量24万平方米,上海万象城购物中心是集合全球顶级奢侈品牌、都会时尚品牌、丰富的寰宇美食、超大型IMAX影院,奥林匹克标准真冰场、五星级KTV、家用家居、儿童亲子、高端超市及地铁博物馆为一体的一站式体验式顶级购物中心。
14万平米共11栋上海万象城都市超甲级写字楼集群,由5栋总部甲级写字楼、6栋超甲级写字楼构成,恢宏巨制,自成一体,构建全新商业生态的城市CBD核心,尽显国际顶级写字楼高端商务气质。
3万平米精品酒店,容纳国际知名酒店品牌以及顶尖软硬件标准配置,领衔3万平米会务、商旅及休闲高端服务的精品之选,商务出行和休闲旅游的绝佳选择。
5万平米生态空中花园,力邀国际顶级景观设计师倾力打造,沪上首个空中花园生态景观办公,提供无限界的开放商务休闲空间体验。
别具一格的业态组合及先进设计理念都将使得上海万象城成为万象城产品线中的一颗璀璨明珠。

matchReg(str) {
    let tempstr = str.match(/[\u4e00-\u9fa5]/g);
    let resultstr = str.substring(str.indexOf(tempstr[0]), 50);
    return resultstr;
}

26、new Date获取及设置时间

let dd = new Date();
//dd.setHours(23);
// dd.setMinutes(39)
// dd.setSeconds(0)
// console.log("getCurrentUser11", dd)
dd.setDate(dd.getDate() + 14); // 获取两周后的日期

27、iOS中Fiexd不起作用

#editorContainer .zxeditor-container .zxeditor-toolbar-wrapper{
    position: sticky;
    position: fixed;
    transform: translateZ(0);
}

28、字符串换行

\r\n

29、html中空格占位符

 

30、蚂蚁组件TextareaItem提交的内容包含换行,如何展示

 
          
               备注留言
              ")}/>
         

31、获取本月开始日期和结束日期

const now = new Date(); // 当前日期
const nowMonth = now.getMonth(); // 当前月
const nowYear = now.getFullYear(); // 当前年
let start = new Date(nowYear, nowMonth, 1).format("yyyy-MM-dd");
let end = new Date(nowYear, nowMonth, 30).format("yyyy-MM-dd");

32、加载html格式字符串并显示出效果

33、js数值计算保留两位小数

1)ceil():将小数部分一律向整数部分进位。Math.ceil(12.2)返回13.0
2)floor():舍去小数,仅保留整数。Math.floor(12.2)返回12.0
3)round():进行四舍五入。Math.round(12.2)返回12.0,Math.round(12.5)返回13.0。

Math.ceil(number * 100) / 100         保留两位小数第三位小数进位
Math.floor(number * 100) / 100       保留两位小数不四舍五入
Math.round(number * 100) / 100 或者 parseFloat(a.toFixed(2))        保留两位小数并四舍五入

34、h5微信JS-SDK内分享
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

export function wxShare(title: any, img?: any, desc?: any) {
    const url = location.href.split("#")[0];
    shhzwechatService.getWxConfig(url).success(d => {
        wx.config(Object.assign({ jsApiList: ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo"] }, d));

        wx.ready(function() {
            wx.onMenuShareAppMessage({
                title: title, // 分享标题
                imgUrl: img || "http://xx/logo.jpg", // 分享图标
                desc: desc || "" // 分享图标
            });

            wx.onMenuShareTimeline({
                title: title,
                desc: desc || "",
                imgUrl: img || "http://xx/logo.jpg" // 自定义图标
            });
        });
    });
}

35、 前端antd-mobiel中 "申请人信息"} className="my-list">类型报错解决方案


前端日常问题记录_第1张图片
FDFFB366991518797B3B0EA61244BD27.png

36、bitech时间判断

import {checkCh} from "./letterlist";
export function getDate(date: string | Date, def?: Date): Date | undefined {
    return date instanceof Date
        ? date
        : date
        ? new Date(
              date
                  .replace(/\-/g, "/")
                  .replace(/T/g, " ")
                  .substr(0, 19)
          )
        : def;
}

export function formatNow(fmt: string = "yyyy-MM-dd") {
    return formatDate(new Date(), fmt);
}

export function formatDateTime(date: Date | string, fmt: string = "yyyy-MM-dd hh:mm:ss") {
    return formatDate(date, fmt);
}

export function formatDate(date: Date | string, fmt: string = "yyyy-MM-dd") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!.format(fmt);
            // tslint:disable-next-line:no-empty
        } catch {}
    }
    return date;
}
/**
 * 获取当前日期N天后日期
 * @param days GetDateStr
 */
export function getDateStr(days?: any, fmt: string = "yyyy-MM-dd") {
    let dd = new Date();
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}

/**
 * 获取指定日期N天后日期
 * @param days GetDateStr
 */
export function getSetDateStr(date: string, days: number, fmt: string = "yyyy-MM-dd") {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}

export function formatFormalDate(date: Date | string, fmt: string = "yyyy-MM-dd hh:mm:ss") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!
                .format(fmt)
                .split(".")[0];
            // tslint:disable-next-line:no-empty
        } catch {}
    }

    return date;
}

export function formatDates(fmt: string = "yyyy-MM-dd") {
    return (date: Date) => formatDate(date, fmt);
}

export function formatDateYtom(date: string) {
    let fmt = "yyyy-MM-dd hh:mm";
    return this.formatDate(date, fmt);
}

export function parseStandard(time: string, format: string = "yyyy-MM-dd hh:mm:ss") {
    let t = new Date(time);
    let tf = function(i) {
        return (i < 10 ? "0" : "") + i;
    };
    return format.replace(/yyyy|MM|dd|hh|mm|ss/g, a => {
        switch (a) {
            case "yyyy":
                return tf(t.getFullYear());

            case "MM":
                return tf(t.getMonth() + 1);

            case "mm":
                return tf(t.getMinutes());

            case "dd":
                return tf(t.getDate());

            case "hh":
                return tf(t.getHours());

            case "ss":
                return tf(t.getSeconds());
            default:
                return "";
        }
    });
}

export function format(this: Date, fmt: string): string {
    const o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        S: this.getMilliseconds() // 毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

    for (const k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));

    return fmt;
}

(Date as any).prototype.format = format;

export function formatTime(date: Date | string, fmt: string = "hh:mm") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!.format(fmt);
            // tslint:disable-next-line:no-empty
        } catch {}
    }

    return date;
}


/**
 * 判断周几
 */
export function getWeekStr(date: string, days: number) {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    let week = dd.getDay();
    let str;
    if (week === 0) {
        str = "周日";
    } else if (week === 1) {
        str = "周一";
    } else if (week === 2) {
        str = "周二";
    } else if (week === 3) {
        str = "周三";
    } else if (week === 4) {
        str = "周四";
    } else if (week === 5) {
        str = "周五";
    } else if (week === 6) {
        str = "周六";
    }
    return str;
}
export function getAvatar(name: string, avatar?: string) {
    if (avatar) {

        return avatar.toUpperCase();
    } else {
        let letter = getChineseHeadLetter(name);
        return letter ? letter.length === 1 ? letter.toUpperCase() : letter.toUpperCase().slice(0, 1) : "";
    }
}
// 参数,中文字符串
// 返回值:拼音首字母串数组
export function getChineseHeadLetter(str) {
    if (typeof (str) !== "string")
        return;
    let arrResult = new Array(); // 保存中间结果的数组

    // 获得unicode码
    let ch = str.charAt(0);
    // 检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理
    let s = checkCh(ch);

    // 处理arrResult,返回所有可能的拼音首字母串数组
    return s.toLowerCase();
}

// function checkCh(ch) {
//     let uni = ch.charCodeAt(0);

//     // 如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数
//     if (uni > 40869 || uni < 19968)
//         return ch;
//     // 检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母
//     return (oMultiDiff[uni] ? oMultiDiff[uni] : (strChineseFirstPY.charAt(uni - 19968)));
// }

37、input输入一个字符自动切换下一个输入框

 this.moveNext.bind(this, e, 1)()}/>
 this.moveNext.bind(this, e, 2)()}/>
 this.moveNext.bind(this, e, 3)()}/>
 this.moveNext.bind(this, e, 4)()}/>
 this.moveNext.bind(this, e, 5)()}/>
 this.moveNext.bind(this, e, 6)()}/>
 this.moveNext.bind(this, e, 7)()}/>
    moveNext(object, index) {
        if (object.target.value.length === 1) {
            $(`.input${index + 1}`).focus();
        }
    }

38、获取两时间间隔多少天,天数查询

export  function timeInterval(starttime, endtime?) {
    let startTime = getDate(starttime); // 开始时间
    let endTime = getDate(endtime ? endtime : new Date()); // 结束时间
    let usedTime = endTime.getTime() - startTime.getTime(); // 相差的毫秒数
    let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
    let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
    let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
    let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
    let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
    return days + '天' + hours + '时' + minutes + '分';
}

39、微信接通银联支付




    BITECH IPARK SAAS
    
    
    
    
    
    
    
    
    


    模拟支付
    

40、获取url问好后参数

    getQueryString(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = this.props.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return null;
    }

41、车牌号查询类似的输入框


前端日常问题记录_第2张图片
屏幕快照 2019-05-22 上午8.58.52.png
 this.moveNext.bind(this, e, 2)()} onKeyDown={e => this.cancelLast.bind(this, e, 2)()} />
   cancelLast(object, index) {
        if (object.keyCode === 8 && (object.target.value.length === 1 || object.target.value.length === 0)) {
            setTimeout(() => {
                $(`.input${index}`).val("");
                $(`.input${index - 1}`).focus();
            }, 30)
        }
    }

    moveNext(object, index) {
        if (object.target.value.length === 1) {
            $(`.input${index + 1}`).focus();
        }
        if (object.target.value.length > 1) {
            let inputValue = $(`.input${index}`).val();
            let inputValues = `${inputValue}`
            $(`.input${index}`).val(inputValues.substring(1, 2))
            $(`.input${index + 1}`).focus();
        }
        if (object.target.value.length === 0) {
            $(`.input${index - 1}`).focus();
        }

    }
    for (let i = 0; i < 8; i++) {
        if (i === 0 && $(`.input${i + 1}`).html()) {
                carNum = carNum + $(`.input${i + 1}`).html();
         } else if ($(`.input${i + 1}`).val()) {
                carNum = carNum + $(`.input${i + 1}`).val();
         }
    }

42、js立即执行防抖函数,防止方法调用重复

debounce(func, wait) {
        let timeout;
        return function () {
            let context = this;
            let args = arguments;
            if (timeout) clearTimeout(timeout);
            let callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args);
        }
    }

实例

let debounceFunLike = this.debounce(this.likeActivity.bind(this), 5000);
debounceFunLike()
debounceFunLike()
debounceFunLike()

43、jquery处理字符串解析dom元素

let $html = $(html);
    $html.find("img").each((index, img) => {
      let $img = $(img);
      let imgSrc = $img.attr("src");
      if (imgSrc && imgSrc.startsWith("./"))
      $img.attr("src", "http://test.bitech.cn/reco8.park/" + imgSrc.substr(1));
    });
    $html.find("a").each((index, a) => {
      let $a = $(a);
      let aHref = $a.attr("href");
      if (aHref && aHref.startsWith("./"))
        $a.attr("href", "http://test.bitech.cn/reco8.park/" + aHref.substr(1));
    });

44、hybrid实现录音及播放

*startRecord({ fail, data, successCall }, { call, put }) {
        // 项目详情语音录入开始
        try {
            try {
                yield put({ type: "showLoading" });
                const result = yield call(startRecord.bind(this, data));
                let formDate = createVoiceData(result, data);
                yield call(quickAddTrackService.discernVoiceAddTrack, formDate);
                // alert(result.get("SourceVideo").name)
                // alert(result.get("SourceVideo").size)
                successCall();
            } catch (error) {
                fail!(error.errmsg);
            } finally {
                yield put({ type: "hideLoading" });
            }
        } catch (error) {
            fail!(error.errmsg);
        }
    }
// 获取音频录音
export function startRecord() {
    let result: Promise | null = null;
    // // 模拟获取音频录音
    // // 有数据测试
    // let file = dataURLtoFile(audioData, "测试");
    // result = Promise.resolve(file);
    // return result;
    // 正式获取音频录音
    result = postBridgeMessage("startRecord");
    if (result) {
        return result.then(({ data, name }) => {
            // alert(`11111${data}${name}`)
            let file = dataURLtoFile(data, name);
            return file;
            // return createData(file, postdata);
        });
    }
}
export function dataURLtoFile(dataurl: string, filename: string) {
    const arr = dataurl.split(","),
        mime = arr![0]!.match(/:(.*?);/)![1],
        bstr = atob(arr[1]);

    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    let date = new Date();
    return new File([u8arr], `${filename}${date.format("yyyyMMddhhmmss")}.wav`, { type: mime });
}
export function createVoiceData(file: any, postdata: any) {
    const formData = new FormData();
    let date = new Date();
    let fileName = `SourceVideo${date.format("yyyyMMddhhmmss")}` + (/^.*?(\.\w+)$/.exec(file!.name)![1] || "");
    if (postdata.ParentID) {
        formData.append("ClueID", postdata.ClueID);
        formData.append("Layer", postdata.Layer);
        formData.append("ParentID", postdata.ParentID);
        formData.append("ChildParentID", postdata.ChildParentID);
        formData.append("ToInputer", postdata.ToInputer);
        formData.append("video", file, fileName);
        formData.append("SourceVideo", file, fileName);
    } else {
        formData.append("ClueID", postdata.ClueID);
        formData.append("video", file, fileName);
        formData.append("SourceVideo", file, fileName);
    }
    return formData;
}

播放录音


 document.getElementById("speekplayer").src = transformUrl(item.Attach.FilePath);
                                                        document.getElementById("speekplayer").play();

45 、web端微信及支付宝支付

*apppay({ error, paytype, payway, order, resourceType, weakthis, callback }, { call, put }) {
        try {
            console.log(
                "支付啊",
                `${window.location.protocol + "//" + window.location.host}/#/resource/roommeet/${
                    Number(resourceType) === ResourceType.MEETING ? "roommeet" : "roomarea"
                }/submitSuccess/${order.ID}`
            );
            const files = new FormData();
            files.append("BindTableName", "BIResourceOrder");
            files.append("Subject", order.ResourceName);
            files.append("TotalAmount", "0.01");
            files.append("BindTableID", `${order.ID}`);
            files.append("TradeChannel", paytype);
            files.append("ParkID", localStorage.ParkID);
            files.append("PaymentType", "NATIVE");
            files.append(
                "ReutrnUrl",
                `${window.location.protocol + "//" + window.location.host}/#/resource/roommeet/${
                    Number(resourceType) === ResourceType.MEETING ? "roommeet" : "roomarea"
                }/submitSuccess/${order.ID}`
            );

            // files.append("ReutrnUrl", this.info.TotalAmount);
            // values.Add("BindTableName", vm.BindTableName);
            // values.Add("Subject", vm.Subject);
            // values.Add("TotalAmount", vm.Amount.ToString());
            // values.Add("BindTableID", vm.BindTableID.ToString());
            // values.Add("TradeChannel", vm.TradeChannel.ToString());
            // values.Add("ParkID", ParkExtensions.GetCurrentParkID()?.ToString());
            // values.Add("ReutrnUrl", AppRuntime.Context.ResolveFullUrl("~/Payment/Success"));

            let result;
            if (Number(payway) === PayWay.alipay) {
                try {
                    // /Cash/Alipay/Pay
                    result = yield call(cashAliPayService.alipay, files);
                    yield put({ type: "input", data: { payBackResult: result } });
                    // document.body.appendChild(result);
                    $(document.body).append(result);
                    // weakthis.goTo(`resourcePaySucceed/${result.id}?bindTableID=${result.id}&payWay=${result.payWay}`);
                } catch (e) {
                    // weakthis.goTo(`resourcePayErr/${e.id}/err`);
                }
            } else if (payway === PayWay.wechat) {
                try {
                    result = yield call(wechatPayService.pay, files);
                    yield put({ type: "input", data: { payBackResult: result, visibleModal: true } });
                    $("#wechatpay").append(result);
                    // weakthis.goTo(`wechatpay`);
                } catch (e) {
                    // weakthis.goTo(`resourcePayErr/${e.id}/err`);
                }
            }
        } catch (e) {
            yield call(error, e);
        } finally {
        }
    }

46、web集成分享

export function shareConfige(text, Desc, url, pic) {
  window._bd_share_config = {
    "common": {
      "bdText": text,
      "bdDesc" : Desc,
      "bdUrl" : url,
      "bdPic": pic,
      "bdSnsKey": {},
      "bdMini": "2",
      "bdMiniList": false,
      "bdStyle": "0",
      "bdSize": "16"
    }, "share": {}
  };

  window._bd_share_main = 0;
  const script = document.createElement("script");
  script.src = "http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=" + ~(-new Date() / 36e5);
  script.className = "shareconfigure";
  document.body.appendChild(script);
}

47、封装前端注入移动端方法桥接的bridge.js


function aliPay(data) {
    if(data.callback){
        window["callback"]=data.callback.bind(this)
    }
//    window["WebViewJavascriptBridge"].callHandler("aliPay", JSON.stringify(data));
    window["webkit"].messageHandlers.aliPay.postMessage(JSON.stringify(data));
}

function wechatPay(data) {
    if(data.callback){
        window["callback"]=data.callback.bind(this)
    }
//    window["WebViewJavascriptBridge"].callHandler("wechatPay",JSON.stringify(data));
    window["webkit"].messageHandlers.wechatPay.postMessage(JSON.stringify(data));
}

function closeWindow() {
    window["webkit"].messageHandlers.closeWindow.postMessage(JSON.stringify(data));
}

使用

function callback(r) {
        alert(r);
    }

aliPay({ orderInfo: info, aliSign: "123456", callback: callback });

48、前端h5检测检测监听网络状态变化

var el = document.body;  
if (el.addEventListener) {  
   window.addEventListener("online", function () {  
     alert("online");}, true);  
   window.addEventListener("offline", function () {  
     alert("offline");}, true);  
}  
else if (el.attachEvent) {  
   window.attachEvent("ononline", function () {  
     alert("online");});  
   window.attachEvent("onoffline", function () {  
     alert("offline");});  
}  
else {  
   window.ononline = function () {  
     alert("online");};  
   window.onoffline = function () {  
     alert("offline");};  
}

49、html滚动div元素到可视范围内

$(ReactDOM.findDOMNode(this.refs[cid as any]) as any)[0].scrollIntoView({behavior: 'smooth'})

50、html滚动到顶部

$(this.refs.scrolref).animate({
    scrollTop: 0
}, 500);

51、webpack打包报javaScript heap out of memory的解决方法
安装:

 npm install -g increase-memory-limit

执行:

 increase-memory-limit

52、antd design Picker组件多级联动

et seasons = [
            {
                label: "河南",
                value: "2013",
                children: [
                    {
                        label: "郑州",
                        value: "123",
                        children: [
                            {
                                label: "金水区",
                                value: "123"
                            },
                            {
                                label: "高新区",
                                value: "456"
                            }
                        ]
                    },
                    {
                        label: "商丘",
                        value: "456"
                    }
                ]
            },
            {
                label: "上海",
                value: "2014",
                children: [
                    {
                        label: "浦东新区",
                        value: "789"
                    },
                    {
                        label: "虹口区",
                        value: "125"
                    }
                ]
            }
        ];
  {}}>
        
                        事项类型
       

持续更新中...

你可能感兴趣的:(前端日常问题记录)