Category Archives: Javasript

Error in JS function referencing public page [How to Solve]

For the website, there are a large number of sharing modules between many pages, such as page header, footer and user bar. Many times, in order to be convenient and easy, we write functions in public modules and call them in other pages. However, when we reference public JS functions, some can be referenced, but some report errors this is because of the problem of JS loading, that is, when the current page is loaded, but some public pages reference public JS before loading, it will report that this function is not found


JS

The results are as follows:

JS referencing public footer

The results are as follows:

from the above two examples, we can know that the loading order of JS is from top to bottom. The header is loaded first – the current page – the footer. Finally, if all the current pages reference the footer that has not been loaded, JS will report “F”_public is not defined”

 

The solution is as follows:

$(document).ready(function () {
        f_public();
})

when the DOM (document object model) has been loaded and the page (including image) has been completely rendered, the ready event will occur; This function is not called until the footer is loaded

page execution sequence in JS

1: Use $(function) {} of jQuery

2: Use $(document). Ready (function() {}) of jQuery; There is no essential difference between the first two. The first is the abbreviation of the second. The second is to execute the method after the document is loaded

3: Use $(window). Load (function() {}) of jQuery

4: Use window. Onload = function() {} the third and fourth methods wait until the whole window is loaded to execute the method body. There is no difference between the two, except that one uses DOM objects and the other uses jQuery objects

5: Statically bind the onload event on the tag, & lt; body onload=”aaa()”> When the body is loaded, the AAA () method is executed

 

So, what is the implementation order of these five methods

Through the following code verification, it is found that:

Use $(function) {} of 1: jQuery and $(document). Ready (function() {}) of 2: jQuery; No matter where the position is placed, the other three methods always take precedence (the reason is that these two methods are executed after the document is loaded, and the last three methods are executed after the whole window page is loaded). The execution order between the two is who is at the top and who takes precedence

Use $(window). Load (function() {}) of 3: jQuery

4: window. Onload = function bbb() {} always takes precedence over & lt; body onload=”aaa()”> Execution. Their execution order is also based on who is at the top and who is first

Use 5: & lt; body onload=”aaa()”> Always last

<script type='text/javascript'>

  window.onload = function(){
    alert("Page loading completed====》onload");
  }

  $(window).load(function(){
    alert("jquery===》window load" );
  })

  $(document).ready(function () {
    alert("jquery====》document ready");
  });

  $(function(){
    alert("jquery====》document onload");
  });

  function aaa(){
    alert("Static labels====》onload");
  }

</script>

<body onload="aaa()">

</body>

 

How to Solve Vue Error: NavigationDuplicated

1. Error information

This error report does not affect the function. If you feel uncomfortable, you can solve it

2. Solutions

Add the following sentences in main. JS


import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Done!

 

[Solved] Node.js runs ES6 default import file error: import m1 from’./m1.js’ ^^ SyntaxError: Unexpected identifier

Solution: Install the plug-in to make NODE.JS support ES6 default import syntax

You can also use plug-ins to support es6

1.node.js terminal install plug-in

npm install --save-dev babel-preset- es2015
npm install --save-dev babel-register

2. Create a new .babelrc file, the configuration content is as follows

{
     "presets": ["es2015" ],
     "plugins" : []
}

3. Join in the entry file of node

require( ‘babel-register’);

After my experiment, only the first two steps can solve the problem.

JQuery Ajax crossdomain cannot be used in IE [How to Solve]

The code is as follows:

$.ajax({
		type:'post',
		url:url,
		data:data,
		dataType:'json',
		xhrFields:{
withCredentials:true
/*
Corresponds to the code in the server
response.addHeader("Access-Control-Allow-Credentials","true");
		response.addHeader("Access-Control-Allow-Origin",origin);
*/
},
crossDomain:true,
success:function(res){
	//。。。
},
error:function(resData){
	//。。。。
}
	});

Open chrome, open fiddler, visit the page, click the button to run, the browser seems to be normal, Fiddler gets an http200 ~! It seems that cross domain access can be achieved by setting crossdomain = true, but it is not perfect

Open IE, test again,,, report an error!?There is no response in fiddler, even the request is not sent out. Strange?Google… Found in an article in stackoverflow:

http://stackoverflow.com/questions/3362474/jquery-ajax-fails-in-ie-on-cross-domain-calls

 

In other words, IE8 uses the so-called xdomainrequest instead of XMLHttpRequest, but jQuery only supports XMLHttpRequest

At present, the best solution is to use jsonp

 

 

 

[Solved] Vue:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#

problem found

Run a previous Vue+webpack vue imitation news website small project, report an error

Because I didn’t study Vue deeply, I always reported this error, and it took a long time (to be exact a whole afternoon ^…^) to find the reason -v-

Uncaught TypeError: Cannot assign to read only property ‘ exports ‘ of object ‘ #<Object> ‘

Click on the wrong file and mark the wrong place as a piece of code:

1 import {normalTime} from  ' ./timeFormat ' ;
 2 module.exports = {
 3    normalTime
 4 };

Is  module.exports;

Solution

Search with Google, and various searches on forums:

The reasons are as follows:

The code above is ok. You can mix require and export. You can’t mix import and module.exports.

The translation means that there is nothing wrong with the code. When webpack is packaged, you can mix require and export in the js file. But import and module.exports cannot be mixed

Because import and module.exports are not allowed to be mixed in webpack 2  ,

The solution is to change it to ES6.

1 import {normalTime} from  ' ./timeFormat ' ;
 2 export default normalTime;

Run again:

 

to sum up

The above is the whole content of this article. I hope that the content of this article can bring some help to your study or work. If you have any questions, you can leave a message and exchange. Thank you for your support to Script Home.

[How to Solve] Cannot set property ‘onclick’ of null

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            //Get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </head>
    <body>
        <input type="button" value="Display effect" id="btn" />    
    </body>
</html>

After the above code is executed, the

To make changes, you need to put the JS file at the bottom of and load it

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>    
    </head>
    <body>
        <input type="button" value="show effect" id="btn" />    
        <script>
            //get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </body>
</html>

The code executes normally

Reason: when the JS file is placed in the head, if the onclick or OnMouseOver event is bound, a similar error will appear as shown in the figure above. The reason is that the order of loading the HTML document you write is from top to bottom, and the JS is executed only after the button node is loaded. Therefore, when the browser parses from top to bottom, the button node bound to onclick cannot be found, so an error is reported

The solution: first, load the JS file at the bottom; Second, use window. Onload = function () {} to wrap JS content

[Solved] VUE Error: Component template should contain exactly one root element. If you are using v-if on mu…

Failed to compile.

./node_modules/vue-loader/lib/template-compiler?{“id”:”data-v-59926570″,”hasScoped”:true,”transformToRequire”:{“video”:[“src”,”poster”],”source”:”src”,”img”:”src”,”image”:”xlink:href”},”buble”:{“transforms”:{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/page/home/Home.vue (Emitted value instead of an instance of Error)

Error compiling template:

<div><el-header class=”animated faedOutUp”><myHeader></myHeader></el-header></div> <div>Home</div>

– Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

@ ./src/page/home/Home.vue 11:0-366

@ ./src/router/index.js

@ ./src/main.js

@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js

 

Error Codes:

<template>
  <div><el-header class="animated faedOutUp"><myHeader></myHeader></el-header></div>
  <div>Home</div>
</template>

It is revised as follows

<template>
  <div>
    <el-header class="animated faedOutUp"><myHeader></myHeader></el-header>
    <div>Home</div>
  </div>
</template>

Save run, error solved

TypeScript error TS1005: ‘;’ expected [How to Solve]

TypeScript error TS1005: ‘;’ expected

If you are using a lower version (1.0.3.0). TSC — version, your version should be set to 2.5.2

In Linux, OSX, check the location of your installation directory, use: which TSC and remove it

Try uninstalling the “global” typescript:
Installing as part of a local dev dependency of your project

npm install typescript --save-dev

Execute it from the root of your project

./node_modules/.bin/tsc

windows :

Remove C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0 directory. Now

install the latest version

npm install -g typescript 

!!!! Try again

[Solved] VUE npm run devevents.js:160 throw er; // Unhandled ‘error’ event listen EADDRIN…

The error is as follows:

Cause of error:

Listen eadrinuse: 8002 means that the current 8002 port is occupied

Solution:

1: Simple and rude: turn off the relevant programs that may be affected and restart them

2

1. Win + R, CMD query whether the port number used is occupied:

Input command: netstat – aon|findstr “8002”

Press enter to display the PID number of the program corresponding to port 8080; As shown in the figure below:

2. Find the corresponding program according to the PID number:

Input command: tasklist | findstr “12452”

Press enter to display the program that occupies the port, as shown in the following figure:

3. Press the shortcut key “Ctrl + Shift + ESC” to call up the Windows Task Manager, and end the program process according to the corresponding name of PID/program. As shown in the figure below: