Tag Archives: js

Vue Error: initialize failed: invalid dom [How to Solve]

An error occurred when ecarts component was introduced into Vue project: “error: initialize failed:invalid dom. ”

I found that I didn’t reach that level at all. The problem I encountered was that I didn’t quote correctly. I split up. Xiaobai grew up in tears and blood. He didn’t talk much nonsense. Write an article and record it.

The main reason is that I didn’t understand the reference method of ecarts component. Here is my solution

<div id="a" style="height:80vh;width:100%" ref="b"></div>

There are two ways, one is Ref

let mychart = this.$echarts.init(this.$refs.b)

A way of using ID

this.$echarts.init(document.getElementById("a"))

The following is the complete code of the ecart component that I quoted. I have highlighted the mistakes I made. I hope it can help you.

<template>
  <div id="a" style="height:80vh;width:100%" ref="b"></div>
</template>
<script>
mounted() {
      this.init()

  },
 
  methods: {
      init(){
          let mychart = this.$echarts.init(this.$refs.b)
          // let mychart = this.$charts.init(document.getElementById("a"))
          //Here, I am the problem here, did not understand the whole id and ref relationship
          let optionline = {
              backgroundColor: '#f0f0f0',
    title: {
        text: 'Folding Line Chart',
        textStyle: {
            align: 'center',
            color: '#99CCFF',
            fontSize: 20,
        },
        top: '5%',
        left: 'center',
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            lineStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(0, 255, 233,0)'
                    }, {
                        offset: 0.5,
                        color: 'rgba(255, 255, 255,1)',
                    }, {
                        offset: 1,
                        color: 'rgba(0, 255, 233,0)'
                    }],
                    global: false
                }
            },
        },
    },
    grid: {
        top: '15%',
        left: '5%',
        right: '5%',
        bottom: '15%',
        // containLabel: true
    },
    xAxis: [{
        type: 'category',
        axisLine: {
            show: true
        },
        splitArea: {
            // show: true,
            color: '#f00',
            lineStyle: {
                color: '#f00'
            },
        },
        axisLabel: {
            color: '#fff'
        },
        splitLine: {
            show: false
        },
        boundaryGap: false,
        data: ['A', 'B', 'C', 'D', 'E', 'F'],

    }],

    yAxis: [{
        type: 'value',
        min: 0,
        // max: 140,
        splitNumber: 4,
        splitLine: {
            show: true,
            lineStyle: {
                color: 'rgba(255,255,255,0.1)'
            }
        },
        axisLine: {
            show: false,
        },
        axisLabel: {
            show: false,
            margin: 20,
            textStyle: {
                color: '#d1e6eb',

            },
        },
        axisTick: {
            show: false,
        },
    }],
    series: [{
            name: 'Total registration',
            type: 'line',
            // smooth: true, // whether smooth
            showAllSymbol: true,
            // symbol: 'image://./static/images/guang-circle.png',
            symbol: 'circle',
            symbolSize: 25,
            lineStyle: {
                normal: {
                    color: "#6c50f3",
                    shadowColor: 'rgba(0, 0, 0, .3)',
                    shadowBlur: 0,
                    shadowOffsetY: 5,
                    shadowOffsetX: 5,
                },
            },
            label: {
                show: true,
                position: 'top',
                textStyle: {
                    color: '#6c50f3',
                }
            },
            itemStyle: {
                color: "#6c50f3",
                borderColor: "#fff",
                borderWidth: 3,
                shadowColor: 'rgba(0, 0, 0, .3)',
                shadowBlur: 0,
                shadowOffsetY: 2,
                shadowOffsetX: 2,
            },
            tooltip: {
                show: false
            },
            areaStyle: {
                normal: {
                    color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(108,80,243,0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(108,80,243,0)'
                        }
                    ], false),
                    shadowColor: 'rgba(108,80,243, 0.9)',
                    shadowBlur: 20
                }
            },
            data: [502.84, 205.97, 332.79, 281.55, 398.35, 214.02, ]
        },
        {
            name: 'Total registration',
            type: 'line',
            // smooth: true, // whether smooth
            showAllSymbol: true,
            // symbol: 'image://./static/images/guang-circle.png',
            symbol: 'circle',
            symbolSize: 25,
            lineStyle: {
                normal: {
                    color: "#00ca95",
                    shadowColor: 'rgba(0, 0, 0, .3)',
                    shadowBlur: 0,
                    shadowOffsetY: 5,
                    shadowOffsetX: 5,
                },
            },
            label: {
                show: true,
                position: 'top',
                textStyle: {
                    color: '#00ca95',
                }
            },

            itemStyle: {
                color: "#00ca95",
                borderColor: "#fff",
                borderWidth: 3,
                shadowColor: 'rgba(0, 0, 0, .3)',
                shadowBlur: 0,
                shadowOffsetY: 2,
                shadowOffsetX: 2,
            },
            tooltip: {
                show: false
            },
            areaStyle: {
                normal: {
                    color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: 'rgba(0,202,149,0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(0,202,149,0)'
                        }
                    ], false),
                    shadowColor: 'rgba(0,202,149, 0.9)',
                    shadowBlur: 20
                }
            },
            data: [281.55, 398.35, 214.02, 179.55, 289.57, 356.14, ],
        },
    ]
          }
          mychart.setOption(optionline)
      }
  }
</script>

“Failed to load resource: net::ERR_FILE_NOT_FOUND” error. The project created by vue-cli 3.0 can run under dev, and an error is reported after packaging, and the page is blank.

Cli3.0 Solutions:
Failed to Load Resource: net::ERR_FILE_NOT_FOUND
Dist /index.html, the introduction is problematic,

The webPack configuration file cannot be found in the project created by Ue-CLi 3.0, because it is encapsulated by Ue-CLi 3.0. You only need to modify it in the vue.config.js file in the root directory of the project (if the project does not have this file, add one directly in the root directory), and set the baseUrl value to ‘./ ‘, and modify as follows

const webpack = require("webpack");
module.exports = {
    pluginOptions: new webpack.ProvidePlugin({
        jQuery: "jquery",
        $: "jquery"
    }),
    baseUrl: './' // ADD these codes
};

Cli2.x Solutions:
Open config/index.js file and build-> AssetsPublicPath is changed to “./ “, which is preceded by a dot.

build: {
  // Template for index.html
  index: path.resolve(__dirname, '../dist/index.html'),

  // Paths
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: './',  // Here
}

Ok, 2. X 3.0 is all done
Please indicate the source of the reprint

How to use C # to get image format without system. Drawing. Common

I wrote a blog to get the correct format of the picture. The code shown in the blog has been working well. Until today, when deploying the program to alicloud function computing, the following error occurred:

System.Drawing is not supported on this platform.

This shows that we can’t use GDI + related functions on the alicloud function computing server. Even so, we can still get the image format by reading the file header

   public static class ImageHelper
    {
        public enum ImageFormat
        {
            Bmp,
            Jpeg,
            Gif,
            Tiff,
            Png,
            Unknown
        }


        public static ImageFormat GetImageFormat(byte[] bytes)
        {
            var bmp = Encoding.ASCII.GetBytes("BM"); // BMP
            var gif = Encoding.ASCII.GetBytes("GIF"); // GIF
            var png = new byte[] {137, 80, 78, 71}; // PNG
            var tiff = new byte[] {73, 73, 42}; // TIFF
            var tiff2 = new byte[] {77, 77, 42}; // TIFF
            var jpeg = new byte[] {255, 216, 255, 224}; // jpeg
            var jpeg2 = new byte[] {255, 216, 255, 225}; // jpeg canon


            if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
            {
                return ImageFormat.Bmp;
            }


            if (gif.SequenceEqual(bytes.Take(gif.Length)))
            {
                return ImageFormat.Gif;
            }


            if (png.SequenceEqual(bytes.Take(png.Length)))
            {
                return ImageFormat.Png;
            }


            if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
            {
                return ImageFormat.Tiff;
            }


            if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
            {
                return ImageFormat.Tiff;
            }


            if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
            {
                return ImageFormat.Jpeg;
            }


            if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
            {
                return ImageFormat.Jpeg;
            }


            return ImageFormat.Unknown;
        }
    }

new  ImageHelper   You need a binary array as a parameter, but that doesn’t mean you need to read all the contents of the file into memory. Using the following code can get better running effect:

    var fn = @"D:\1.jpg";
    using (var fs = File.OpenRead(fn))
    {
        var header = new byte[10];
        await fs.ReadAsync(header, 0, 10);
        var ext = ImageHelper.GetImageFormat(header);
        ext.Dump();
    }

JS bug Log Uncaught TypeError: Cannot read property ‘previoustSibling‘ of null

The program code is:

 <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Visit the Dangdang shopping cart page node</title>
    <link type="text/css" rel="stylesheet" href="css/cartStyle.css" />
</head>
<body>

<div class="content">
    <div class="logo">
        <img src="images/dd_logo.jpg"><span onclick="close_plan();">close</span>
    </div>
    <div class="cartList" id="cartList">
        <ul>
            <li>¥<input type="text" name="price" value="21.90"></li>
            <li><input type="button" name="minus" value="-" onclick="minus(0);"><input type="text" name="amount" value="1"><input type="button" name="plus" value="+" onclick="plus(0);"></li>
            <li id="price0">¥21.90</li>
            <li><p  onclick="collection();">add</p><p onclick="del();">del</p></li>
        </ul>
        <ul>
            <li>¥<input type="text" name="price" value="24.00"></li>
            <li><input type="button" name="minus" value="-" onclick="minus(1);"><input type="text" name="amount" value="1"><input type="button" name="plus" value="+" onclick="plus(1);"></li>
            <li id="price1">¥24.00</li>
            <li><p  onclick="collection();">add</p><p onclick="del();">del</p></li>
        </ul>
        <ol>
            <li id="totalPrice">&nbsp;</li>
            <li><span onclick="accounts()">payout</span></li>
        </ol>
    </div>
    <div id="money"></div>
</div>
<script type="text/javascript" src="js/shopping.js">


</script>
<script type="text/javascript">
	function accounts(){
	     var num1=document.getElementById("cartList").firstChild.lastChild.previoustSibling.innerHTML;
		 var num2=document.getElementById("cartList").firstChild.nextSibling.lastChild.previousSibling.innerHTML;
		 var num3=document.getElementById("totalPrice").innerHTML;
		 var num4="Information about your current purchase is as follows:<br/>White Rock:White says: "+num1+"<br/>Island Bookstore: "+num2+"<br/>Total items:"+num3;
		 document.getElementById("money").innerHTML=num4;
	    }
</script>
</body>
</html>

Display error:

Uncaught TypeError: Cannot read property 'previoustSibling' of null
    at accounts (shopping.html:39)
    at HTMLSpanElement.onclick (shopping.html:29)

Error reason: unable to read space

Solution:
add element to the get node in function accounts()

The correct function code is:

function accounts(){
	     var num1=document.getElementById("cartList").firstElementChild.lastElementChild.previousElementSibling.innerHTML;
		 var num2=document.getElementById("cartList").firstElementChild.nextElementSibling.lastElementChild.previousElementSibling.innerHTML;
		 var num3=document.getElementById("totalPrice").innerHTML;
		 var num4="Information about your current purchase is as follows:<br/>White Rock:White says: "+num1+"<br/>Island Bookstore: "+num2+"<br/>Total items:"+num3;
		 document.getElementById("money").innerHTML=num4;
	    }

Net Q & A: how to avoid the exception thrown by max() on emptyenumerable?

Consultation area

Naor:

I have the following query:


int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                          .Max(x => x.ShoeSize);

If workers. Where (x = & gt; x. Companyid = = 8) if no workers are found, the above code will throw an exception.

Now the idea is: query can return 0 if it can't be found, but don't throw an exception. How can I modify the query above?

Answer area

Ron K.:

You can use the extension method of IEnumerable defaultifempty() to avoid this embarrassment. Refer to the following code.


    class Program
    {
        static void Main(string[] args)
        {
            List<Worker> Workers = new List<Worker>()
            {
                new Worker(){ CompanyId=1, CompanyName="tweet", ShoeSize=10 },
                new Worker(){ CompanyId=2, CompanyName="google", ShoeSize=20 },
            };

            int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                          .Select(x => x.ShoeSize)
                          .DefaultIfEmpty(0)
                          .Max();

            Debug.WriteLine($"maxShoeSize={maxShoeSize}");
        }

    }

    class Worker
    {
        public int CompanyId { get; set; }

        public string CompanyName { get; set; }

        public int ShoeSize { get; set; }
    }

Output results:


maxShoeSize=0

Of course, the above 0 is not necessary. You can change it to any other number.

CptRobby:

Although the plan provided by the man upstairs can work normally, it doesn't look very eye-catching. It can be transformed into the following one.


    int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
                             .Select(x => (int?)x.ShoeSize)
                              .Max() ?? 0;

Does the code look a little lengthy?The best way is to customize a extension method , as shown in the following code:


public static int MaxOrDefault<T>(this IQueryable<T> source, Expression<Func<T, int?>> selector, int nullValue = 0)
{
    return source.Max(selector) ?? nullValue;
}

For simplicity, this extension only deals with the int type. You can change it to any type, such as: (long, double,...), and then you can continue to reform the caller.


int maxShoeSize = Workers.Where(x => x.CompanyId == 8).MaxOrDefault(x => x.ShoeSize);

I hope my answer can help more people.

Comment area

Xiaobian never dares to do Max on the empty collection , after all, it's not once or twice, so every time we judge whether there is a value in the collection in advance, and then execute Max , we didn't expect that there are magic extension methods defaultifempty and empty type that can help us to do it, and we all forget about sensory science????????????.

How to Use DOM to operate CSS

    1. Modify styles through JS: the styles modified by this method are inline styles with high priority. However, if “! Important” is used in the style, the modification of JS will not work.
	Syntax: element.style.styleName = styleValue ;      
	The style value must be a string
	Note: If the style of css contains " - " , this name is not legal in JS, you need to change this style name to camel naming, remove the " - " and change the
	initial letter to uppercase.

Read style:

	Syntax: element.style.styleName

The styles set and read through the style property are inline styles

    1. get the display style of the current element:
	Syntax: element.currentStyle.styleName 
	currentStyle is only supported by IE browser

In other browsers, you can use the getcomputedstyle() method to get the current style of the element. This method is a window method and can be used directly. This method will return a style object that encapsulates the corresponding style of the current element.

	Two parameters are required
	The first: the element to get the style
	The second: you can pass a pseudo-element, which is usually null

Note: the styles obtained through currentstyle and getcomputestyle are read-only and cannot be modified. If you want to modify them, you must use the style property </OL> to modify them

The addition, deletion and modification of DOM in JS Foundation

    1. document.createElement (); you need to pass in a tag name as a parameter. You will create a corresponding node according to the tag name and return the node. document.createTextNode (); you need to pass in a text content as the parameter appendChild ()
	Usage: parent element.appendChild( child node ).

A child of a node can be inserted before the new node

	Usage: Parent node. insertBefore( new node, old node );

Replacechild(); replace child node

	Usage: parent.replaceChild( new node, old node );

Removechild(); can delete a child node

	Usage: parent.removeChild(child node).

InnerHTML can also be used to add dom. Generally, the two methods are combined.

	e.g. city.innerHTML += " <li>GuangZhou</li> ";

Confirm (“); a prompt box with confirm and Cancel buttons will pop up. If the user clicks confirm, it will return true; otherwise, it will return false </ OL>

JS Mobile Page to determine whether it is iPhone X, and then set the corresponding height of the element?

In developing H5 projects, it is sometimes necessary to judge the iPhone model and distinguish whether it is iPhone X or not. The implementation is as follows:

methods: {
 isIPhoneX() {
   let u = navigator.userAgent;
   let isIOS = !!u.match(/\(i[^;]+;( U;)?CPU.+Mac OS X/); 
   if (isIOS) {
     if (screen.height == 812 && screen.width == 375) {
       //is iphoneX
     } else {
       //not iphoneX
     }
   }
 }
}

Then set the element height dynamically according to ref, as follows:

methods: {
 isIPhoneX() {
    let u = navigator.userAgent;
    let isIOS = !!u.match(/\(i[^;]+;( U;)?CPU.+Mac OS X/); 
    if (isIOS) {
      if (screen.height == 812 && screen.width == 375) {
        //is iphoneX
        this.$refs.punchcontent.style.height = "calc(100vh - 114px)"
      } else {
        //not iphoneX
        this.$refs.punchcontent.style.height = "calc(100vh - 80px)"
      }
    }else{
      //android
      this.$refs.punchcontent.style.height = "calc(100vh - 80px)"
    }
  }
}

Note: when the
isIPhoneX() method is called, it needs to be invoked in the mounted method, otherwise the setting height is invalid (the first step is to get the DOM node).

Crypto JS decrypts malformed UTF-8 data

When using crypto JS to decrypt, an error may be reported:

Malformed UTF-8 data
Error: Malformed UTF-8 data
    at Object.stringify (d:\StudeyCode\myStudy\encryptDemo\routes\encrypt\crypto-js.js:478:27)
    at WordArray.init.toString (d:\StudeyCode\myStudy\encryptDemo\routes\encrypt\crypto-js.js:215:41)
    at decryptByDESModeCBC (d:\StudeyCode\myStudy\encryptDemo\routes\encrypt\crypto.js:90:22)
    at testSign (d:\StudeyCode\myStudy\encryptDemo\routes\test.js:34:18)
    at Layer.handle [as handle_request] (d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\layer.js:95:5)
    at next (d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\layer.js:95:5)
    at d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (d:\StudeyCode\myStudy\encryptDemo\node_modules\express\lib\router\index.js:335:12)

The reason for the error is: when des decrypts, if the encrypted data is not an integral multiple of 8, the above error will be reported,
solution: encrypt the data, and then encrypt it with Base64. When decrypting, first decrypt it with Base64, and then decrypt it with DES. The above problems can be solved.

[jQuery] jQuery operates on JSON strings or JSON objects

preface

Most of the time, you need to convert a JSON string to a JSON object, and then process it in a loop, or convert a JSON object to a JSON string as a parameter and pass it to the relevant interface. Next, we will introduce several conversion methods

Assume that the JSON string is

Var jsonstr = ‘[{“Id”: 1, “title”: “Zhang San”, “sex”: “male”}, {“Id”: 2, “title”: “Li Si”, “sex”: “male”}]’;

Assume that the JSON object is

Var jsonobj = [
{
“Id”: 1,
“title”: “Zhang San”,
“sex”: “male”
},
{
“Id”: 2,
“title”: “Li Si”,
“sex”: “male”
}
]

1、 Convert JSON string to JSON array object

1、eval()

var jsonObj = eval('(' + jsonStr + ')');

2、JSON.parse()

var jsonObj = JSON.parse(jsonStr);

Prev

var jsonObj = JSON.parse(jsonStr);

2、 Convert JSON object to JSON string

JSON.stringify ()

var jsonStr = JSON.stringify(jsonObj);

3、 Loop JSON object

for (var i = 0; i < jsonObj.length; i++) {

    var name= jsonObj[i].Title;

}

 

Solution to report undefined a error when using jquery

When the project uses easyUI, the foreground reports an error, type error: A is undefined. I see that the error location is actually the source code of JQ… It’s impossible. I searched a lot of information on the Internet, but I didn’t solve the problem. After nearly a month’s thinking, I seem to have found the cause of this problem. It may not be right. It only represents personal profile. If there is a positive solution, please let me know. Thank you.

The error screenshot is as follows:

The reasons are as follows: I have such a piece of code in JS:

 $('#cargo_info').datagrid().datagrid('getPager');

Note that this code is not put in any function, nor is it wrapped with $(function () {}). Just this sentence is put directly in JS code. This is all the cases that report this error in my project. My preliminary analysis is because JS thinks that there is no method to call this sentence, so it reports an error.

Solution: wrap the isolated statements in JS with $(function () {}), or write them in a function,

<pre name="code" class="javascript">$(function(){
    $('#cargo_info').datagrid().datagrid('getPager');
})


Like this, you can’t make a mistake at the front desk