Turn mosaic character escape

  In the program, often written string concatenation, the most common way is to splice in a string return to the page, and then let the browser rendering into html code.

Now es6 has been a lot, but for some reason, some projects can only use the most primitive plus sign "+" stitch, so there will be a situation of use; Consider the following code:

1 var stringify_json = JSON.stringify(rowObject);
2 var str2 = 1;
1 str +="<input onclick='del_id("+stringify_json+","+str2+")' type='button' value='删除' />";
2 function del_id(a,b){
3     console.log(a);
4     console.log(b);
5 }

 

The above is the life of the code, this time is no problem, you put str returns directly to the page, the page can be properly resolved, click on this button can also be printed; Here is the result of printing

Print the structure is no problem. But when we put the string into str2, I found the page to start the error.

That is, the above code into str2 = "string" when being given a start page; Here is the result of rendering false information, and pages;

I found that this is not in accordance with the string concatenation up, so js think this is a process, so the above error occurred.

So we splicing of time, you need to put quotation marks on both sides of the string, so there is the following code:

1 str +="<input onclick='del_id("+stringify_json+",'"+str2+"')' type='button' value='删除' />";

Then on page rendering it is like this.

In other words, html parser to parse the string in front of the quotes when they think this period is complete, so the page will direct error, and that is, we need the single quotation marks on stitching, into double quotes;

The following is a screenshot of my editor, I directly in the code above in single quotes to double quotes.

Editor str2 not directly as a variables. This certainly does not work, so this time we need to spend our transfer character "\" a;

1 str +="<input onclick='del_id("+stringify_json+",\""+str2+"\""+")' type='button' value='删除' />";

This is after the transfer plus character, that is to say, \ back quotes, not as we are spliced ​​thing, but that simply means he is quoted. In this case, we can normally print.

---------------- gorgeous dividing line -----------------------------

There are already many projects with es6 the fine, es6 a more beautiful way to string concatenation; see the link below

https://www.cnblogs.com/newze/p/7535470.html

This article was written well. You can own inspection;

Guess you like

Origin www.cnblogs.com/daniao11417/p/10986065.html