Tag Archives: javascript

Deep understanding of async await asynchronous programming synchronization

we know that the JavaScript code executes sequentially, so let’s look at the result of the execution of the following code:

function a(){
    return new Promise((resolve,reject)=>{
        resolve("a")
    })
}
function b(){
    return new Promise((resolve,reject)=>{
      setTimeout(() => {
        resolve("b")
      }, 2000);
    })
}
function c(){
    return new Promise((resolve,reject)=>{
        resolve("c")
    })
}
 function execute(){
    let a1= a()
    a1.then(res=>{
        console.log(res);
    })
    let b1= b()
   b1.then(res=>{
    console.log(res);
   })
    let c1= c()
   c1.then(res=>{
    console.log(res);
   })
}
execute()


so how to show it in order, that is, C wait for B to execute after the execution. The following

function a(){
    return new Promise((resolve,reject)=>{
        resolve("a")
    })
}
function b(){
    return new Promise((resolve,reject)=>{
      setTimeout(() => {
        resolve("b")
      }, 2000);
    })
}
function c(){
    return new Promise((resolve,reject)=>{
        resolve("c")
    })
}
async function execute(){
    let a1=await a()
    //用了await之后,就不用.then了直接得到结果
   console.log(a1)
    let b1=await b()
    console.log(b1)
    let c1=await c()
   console.log(c1)
}
execute()

How to restrict input field to only input pure numbers in HTML

limit input input box can only enter pure Numbers

1, the onkeyup = "value, value = replace (/ [^ \] d/g,") "

USES the onkeyup event, and has the bug, that is, in the state of Chinese input method, after Chinese characters are input, enter directly, the letter

will be input directly

2, onchange = "value, value = replace (/ [^ \] d/g,") "

USES the onchange event. After input content, only the input loses focus will get the result, and the response

cannot be made when input

3, the oninput = "value, value = replace (/ [^ \] d/g,") "

USES the oninput event, which perfectly solves the above two problems. There are no other problems in the test for the time being.

code example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>input</title>
</head>
<body>
    只能输入纯数字的输入框:<input type="text" name="" oninput="value=value.replace(/[^\d]/g,'')">
</body>
</html>

above code has been tested in Google, firefox, baidu, UC, IE11, 360 fast, QQ, Edge browser, please feel free to use,

thanks for qq_38726717, xiao xiao xin feedback in the comments section.

JS opens a new tab( window.open Application)

js how to open a new TAB

in & lt; a> The tag can be opened by setting target= “_blank”. But sometimes you need Javascript to open a new tag, so how do you do that?Here’s how:
window.open(” http://www.wlzhys.com “); .
or:
Windows open (” http://www.wlzhys.com “, “_blank”); // note that the second parameter
, some people may wonder, window.open() is not used to open a new window, how can you open a new TAB?In fact, the browser will only open a new window when the third property
is specified in window.open() (i.e. the characteristics of the new window). If the third property is not specified, the browser will only open a new TAB in the current window (in IE, if the URL to be opened does not belong to the same main domain name as the URL of the current
page, the new window will be opened; In Chrome, if the window.open() function is called not by mouse and keyboard events, but directly by the page, or via a
timer, etc., then a new window is opened instead of a TAB. In addition, the following applies to < a> The target parameter of the tag also applies to the name parameter of window.open() :

note:
1. In IE, if the domain you want to open does not belong to the same primary domain as the current domain, it will open in a new window (< a> The tag does the same. 2. In Chrome, if the window.open() function is called not by mouse and keyboard events, but either directly by the page or via timers (including those triggered by mouse and keyboard), then a new window is opened instead of a TAB. 3. In a new window or tag, the _parent and _top arguments of window.open() are invalid (valid only in frame). The framename parameter can be set to the name value of the frame in the current page, the name value of the new window, or the name value of the new tag.
[footnote]
window.open(url,target,init); //URL represents the page address; 1. Open the link in the new TAB/page
window.open(‘ http://www.wlzhys.com ‘, ‘Target’, “);

2, open the link
(1) window.open(‘ http://www.wlzhys.com ‘, ‘_self’, “);
(2) window.location.href= ‘http://www.wlzhys.com’;

JavaScript realizes the longest substring of non repeated characters

simple rough direct code

is easy to understand with console, the code is as follows:

    var lengthOfLongestSubstring = function (s) {
      var arr = [];
      var max = 0;
      for (let index = 0; index < s.length; index++) {
        var a = arr.indexOf(s[index]);
        console.log(a, s[index], 222)
        if (a != -1) {
          arr.splice(0, a + 1)
          console.log(111, arr, max)
        }
        arr.push(s.charAt(index))
        console.log(arr, 222)
        max = Math.max(arr.length, max)
      }
      return console.log(max, arr)

    };
    lengthOfLongestSubstring('abcdeasasas')

JS prompt cannot read property ‘style’ of undefined

"order": [[6, "asc"]],

Instead of

"order": [[0, "asc"]],

reason, only 3 columns, I chose column 6 to sort…

so there’s a sense that it’s out of bounds, so the error is

<div class="box-body">
    <table class="table table-bordered table-striped" id="mytable" role="grid" aria-describedby="user" style="width: 100%;">
        <thead>
        <tr>
            <th>名字</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        </thead>
    </table>
</div>

<script>
    var table;

    $(function () {
        table = $('#mytable').DataTable({
            "sScrollY": $(this).height() -280,
            "serverSide": true,
            "processing": true,
            "paging": true,
            "lengthChange": false,
            "searching": false,
            "ordering": false,
            "info": true,
            "autoWidth": true,
            "order": [[0, "asc"]],//按照第几列排序
            "pageLength": 10,
            "bLengthChange": true,
            "oLanguage": lang,
            "ajax": {
                "url": "${CONTEXT_PATH}/admin/essay/voteList",
                "type": "POST",
                "dataSrc": "data",
                "data": function (d) {
                    d.extra_search = $("#form").serialize();
                }
            }, 
            "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 5 ] }],
            "columns": [
                {"data": "name"},
                {"data": "age"},
                {"data": "sex"}
            ]
        });
    });


</script>


JavaScript emoticon package encryption

  • after reading this article you may feel that you know nothing about the power of JavaScript!
  • let’s see what kind of encryption this is!
  • is the author of the encryption: from Japan Yosuke HASEGAWA
  • his project address: http://utf-8.jp/public/aaencode.html

    we encrypt a string of JS code with this method: alert(” HelloWorld! );

    function aaencode( text )
    {
        var t;
        var b = [
    		"(c^_^o)",
    		"(゚Θ゚)",
    		"((o^_^o) - (゚Θ゚))",
    		"(o^_^o)",
    		"(゚ー゚)",
    		"((゚ー゚) + (゚Θ゚))",
    		"((o^_^o) +(o^_^o))",
    		"((゚ー゚) + (o^_^o))",
    		"((゚ー゚) + (゚ー゚))",
    		"((゚ー゚) + (゚ー゚) + (゚Θ゚))",
    		"(゚Д゚) .゚ω゚ノ",
    		"(゚Д゚) .゚Θ゚ノ",
    		"(゚Д゚) ['c']",
    		"(゚Д゚) .゚ー゚ノ",
    		"(゚Д゚) .゚Д゚ノ",
    		"(゚Д゚) [゚Θ゚]"
            ];
    	var r = "゚ω゚ノ= /`m´)ノ ~┻━┻   //*´∇`*/ ['_']; o=(゚ー゚)  =_=3; c=(゚Θ゚) =(゚ー゚)-(゚ー゚); "; 
    	
    	if( /ひだまりスケッチ×(365|356)\s*来週も見てくださいね[!!]/.test( text ) ){
    		r += "X=_=3; ";
    		r += "\r\n\r\n    X/_/X < \"来週も見てくださいね!\";\r\n\r\n";
    	}
        r += "(゚Д゚) =(゚Θ゚)= (o^_^o)/ (o^_^o);"+
            "(゚Д゚)={゚Θ゚: '_' ,゚ω゚ノ : ((゚ω゚ノ==3) +'_') [゚Θ゚] "+
            ",゚ー゚ノ :(゚ω゚ノ+ '_')[o^_^o -(゚Θ゚)] "+
            ",゚Д゚ノ:((゚ー゚==3) +'_')[゚ー゚] }; (゚Д゚) [゚Θ゚] =((゚ω゚ノ==3) +'_') [c^_^o];"+
            "(゚Д゚) ['c'] = ((゚Д゚)+'_') [ (゚ー゚)+(゚ー゚)-(゚Θ゚) ];"+
            "(゚Д゚) ['o'] = ((゚Д゚)+'_') [゚Θ゚];"+
            "(゚o゚)=(゚Д゚) ['c']+(゚Д゚) ['o']+(゚ω゚ノ +'_')[゚Θ゚]+ ((゚ω゚ノ==3) +'_') [゚ー゚] + "+
            "((゚Д゚) +'_') [(゚ー゚)+(゚ー゚)]+ ((゚ー゚==3) +'_') [゚Θ゚]+"+
            "((゚ー゚==3) +'_') [(゚ー゚) - (゚Θ゚)]+(゚Д゚) ['c']+"+
            "((゚Д゚)+'_') [(゚ー゚)+(゚ー゚)]+ (゚Д゚) ['o']+"+
            "((゚ー゚==3) +'_') [゚Θ゚];(゚Д゚) ['_'] =(o^_^o) [゚o゚] [゚o゚];"+
            "(゚ε゚)=((゚ー゚==3) +'_') [゚Θ゚]+ (゚Д゚) .゚Д゚ノ+"+
            "((゚Д゚)+'_') [(゚ー゚) + (゚ー゚)]+((゚ー゚==3) +'_') [o^_^o -゚Θ゚]+"+
            "((゚ー゚==3) +'_') [゚Θ゚]+ (゚ω゚ノ +'_') [゚Θ゚]; "+
            "(゚ー゚)+=(゚Θ゚); (゚Д゚)[゚ε゚]='\\\\'; "+
            "(゚Д゚).゚Θ゚ノ=(゚Д゚+ ゚ー゚)[o^_^o -(゚Θ゚)];"+ 
    		"(o゚ー゚o)=(゚ω゚ノ +'_')[c^_^o];"+//TODO
            "(゚Д゚) [゚o゚]='\\\"';"+ 
            "(゚Д゚) ['_'] ( (゚Д゚) ['_'] (゚ε゚+";
        r += "(゚Д゚)[゚o゚]+ ";
        for( var i = 0; i < text.length; i++ ){
            n = text.charCodeAt( i );
            t = "(゚Д゚)[゚ε゚]+";
    		if( n <= 127 ){
    			t += n.toString( 8 ).replace( /[0-7]/g, function(c){ return b[ c ] + "+ "; } );
    		}else{
    			var m = /[0-9a-f]{4}$/.exec( "000" + n.toString(16 ) )[0];
    			t += "(o゚ー゚o)+ " + m.replace( /[0-9a-f]/gi, function(c){ return b[ parseInt( c,16 ) ] + "+ "; } );
    		}
            r += t;
    
        }
        r += "(゚Д゚)[゚o゚]) (゚Θ゚)) ('_');";
        return r;
    }
    

    yes we got a bunch of cute memes!!

    ゚ω゚ノ= /`m´)ノ ~┻━┻   //*´∇`*/ ['_']; o=(゚ー゚)  =_=3; c=(゚Θ゚) =(゚ー゚)-(゚ー゚); (゚Д゚) =(゚Θ゚)= (o^_^o)/ (o^_^o);(゚Д゚)={゚Θ゚: '_' ,゚ω゚ノ : ((゚ω゚ノ==3) +'_') [゚Θ゚] ,゚ー゚ノ :(゚ω゚ノ+ '_')[o^_^o -(゚Θ゚)] ,゚Д゚ノ:((゚ー゚==3) +'_')[゚ー゚] }; (゚Д゚) [゚Θ゚] =((゚ω゚ノ==3) +'_') [c^_^o];(゚Д゚) ['c'] = ((゚Д゚)+'_') [ (゚ー゚)+(゚ー゚)-(゚Θ゚) ];(゚Д゚) ['o'] = ((゚Д゚)+'_') [゚Θ゚];(゚o゚)=(゚Д゚) ['c']+(゚Д゚) ['o']+(゚ω゚ノ +'_')[゚Θ゚]+ ((゚ω゚ノ==3) +'_') [゚ー゚] + ((゚Д゚) +'_') [(゚ー゚)+(゚ー゚)]+ ((゚ー゚==3) +'_') [゚Θ゚]+((゚ー゚==3) +'_') [(゚ー゚) - (゚Θ゚)]+(゚Д゚) ['c']+((゚Д゚)+'_') [(゚ー゚)+(゚ー゚)]+ (゚Д゚) ['o']+((゚ー゚==3) +'_') [゚Θ゚];(゚Д゚) ['_'] =(o^_^o) [゚o゚] [゚o゚];(゚ε゚)=((゚ー゚==3) +'_') [゚Θ゚]+ (゚Д゚) .゚Д゚ノ+((゚Д゚)+'_') [(゚ー゚) + (゚ー゚)]+((゚ー゚==3) +'_') [o^_^o -゚Θ゚]+((゚ー゚==3) +'_') [゚Θ゚]+ (゚ω゚ノ +'_') [゚Θ゚]; (゚ー゚)+=(゚Θ゚); (゚Д゚)[゚ε゚]='\\'; (゚Д゚).゚Θ゚ノ=(゚Д゚+ ゚ー゚)[o^_^o -(゚Θ゚)];(o゚ー゚o)=(゚ω゚ノ +'_')[c^_^o];(゚Д゚) [゚o゚]='\"';(゚Д゚) ['_'] ( (゚Д゚) ['_'] (゚ε゚+(゚Д゚)[゚o゚]+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+((゚ー゚) + (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚Θ゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) - (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+((゚ー゚) + (o^_^o))+ (o^_^o)+ (゚Д゚)[゚o゚]) (゚Θ゚)) ('_');
    

    however, these memes are not as cute as you might think, and they are just as damaging!!

    his corresponding decryption method is

    function decrypt (text) {
    	var evalPreamble = "(\uFF9F\u0414\uFF9F) ['_'] ( (\uFF9F\u0414\uFF9F) ['_'] (";
    	var decodePreamble = "( (\uFF9F\u0414\uFF9F) ['_'] (";
    	var evalPostamble = ") (\uFF9F\u0398\uFF9F)) ('_');";
    	var decodePostamble = ") ());";
    
    	// strip beginning/ending space.
    	text = text.replace(/^\s*/, "").replace(/\s*$/, "");
    
    	// returns empty text for empty input.
    	if (/^\s*$/.test(text)) {
    		return "";
    	}
    	// check if it is encoded.
    	if (text.lastIndexOf(evalPreamble) < 0) {
    		throw new Error("Given code is not encoded as aaencode.");
    	}
    	if (text.lastIndexOf(evalPostamble) != text.length - evalPostamble.length) {
    		throw new Error("Given code is not encoded as aaencode.");
    	}
    
    	var decodingScript = text.replace(evalPreamble, decodePreamble)
    							 .replace(evalPostamble, decodePostamble);
    	return eval(decodingScript);
    }
    

JavaScript / JS native dynamic introduction of external CSS files and dynamic insertion of CSS code fragments

there are two ways to dynamically create CSS styles:
1. Introduce external CSS files
2. Insert CSS snippet
how to insert CSS external files dynamically:

function loadStyle(url){
var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = url;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(link);
}
loadStyle('test.css');

dynamically loads CSS snippet

function loadCssCode(code){
    var style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    //for Chrome Firefox Opera Safari
    style.appendChild(document.createTextNode(code));
    //for IE
    //style.styleSheet.cssText = code;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');

IE & lt; link> The tag is considered a special tag and its children cannot be accessed, so stylesheet.csstext is used, and errors thrown by IE are caught using a try catch statement, with the following compatible code:

function loadCssCode(code){
var style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    try{
        //for Chrome Firefox Opera Safari
        style .appendChild(document.createTextNode(code));
    }catch(ex){
        //for IE
        style.styleSheet.cssText = code;
    }
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');

adds styles to the page in real time, so you can react instantly on the page.

Use XMLHttpRequest of JavaScript to send data to the background

1. Would like to send data to add to the FormData in (using XMLHttpRequest must add data to the FormData or it will protect the wrong)

2. A new XMLHttpRequest out

3. Use the open method to specify the way to request (post or get) and URL

4. Set the callback method

5. The most important step: use the send method (data is stored in the FormData inside the parentheses) to send data

ERROR in static/js/app.xxxxxxx.js from UglifyJs Unexpected token: operator (>)

:
vue family barrel USES the vue-qrcode-directive component to generate the two-dimensional code in the project. There is no error in using NPM run dev in the development process. To NPM run build packaging ERROR, such as the ERROR in the static/js/app f1ecb9a5673e78cc442b. Js from UglifyJs Unexpected token: operator (& gt;) [./~/_vue – [email protected] @ vue – qrcode – directive/index, js: 4, 0] [static/js/app. F1ecb9a5673e78cc442b. Js: 17412]

analysis reason :
weback default webpack. Optimize. UglifyJsPlugin cannot compress es6 code files. Along the way, we can simply convert es6 code to ES5 using Babel.
the reason must still be on webpack.config.js. After repeated observations. The problem occurred in the loader configuration, where an item was configured for js file transformation.

solution : (the same problem occurs in _quill-image-drop-module, _vue-qrcode-directive)

module: {
  rules: [
    {
        test: /\.js$/,
        loader: "babel-loader",
        include: [
          resolve("src"),
          resolve("test"),
          resolve(
            "node_modules/[email protected]@quill-image-drop-module"
          ),
          resolve(
            "node_modules/[email protected]@vue-qrcode-directive"
          )
        ],
      }
  ]
}