The recent JS note, is to be able to see more than previously did not understand the place

Source: Internet
Author: User
Tags set cookie setcookie truncated

Tag:fine   ...    Extract    content   number     decimal     Order     submit data     shorthand    

The

1,
//js implementation retains two decimal places
function Returnfloat (value) {
var value = Math.Round (parsefloat (value) * +)/+;
Var XSB = Value.tostring (). Split (".");
if (xsb.length = = 1) {
value = value.tostring () + ". xx";
return value;
}
if (Value.length > 1) {
if (Xsb[1].length < 2) {
value = value.tostring () + "0";
}
return value;
}
}
2,
//Get progress on all work of the project
function allprojectlist () {
var xhr = new XMLHttpRequest ();
var url = ' http://10.122.84.35:8080/imp4sep/project/schedule/all?projectId= ' + projectid + ' &&stage= ' + Stagenumber;
Xhr.open ("GET", url, false);//Synchronous request
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4 &&am P Xhr.status = = () {
var allproject = xhr.responsetext;
//alert (allproject);
Allprojectinfo (Allproject);
}
};
//xmlhttp.open ("GET", url, True), and the third argument is true for async

3.
JS regular gets the URL parameter value
function getquerystring (name) {
var reg = new RegExp ("(^|&)" + name + "= ([^&]*) (&|$)");
var r = window.location.search.substr (1). Match (REG);
if (r! = null) return unescape (r[2]); return null;
}

4.
The encapsulation function remembers to return the value;
Can be set to apply a variable to the global var TT = ""; put it in the global place.

5.
JS Settings Cookie

Set cookies
function Setcookie (CNAME, cvalue, exdays) {
var d = new Date ();
D.settime (D.gettime () + (Exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toutcstring ();
Document.cookie = cname + "=" + Cvalue + ";" + expires;
}
Clearing cookies
function ClearCookie (name) {
Setcookie (Name, "",-1);
}

Get cookies
function GetCookie (name) {
var arr, Reg = new RegExp ("(^|)" + name + "= ([^;] *)(;|$)");
if (arr = Document.cookie.match (reg))
Return (arr[2]);
Else
return null;
}
JS Set Cookie End

6,
//js set navigation bar Toggle Highlight
function myselct (ID) {
if (id! = ID) {//Click the current ID of Li no change, click on the other ID of Li when start if statement
var presect = doc Ument.getelementbyid (' Sect ' + ID); Not the ID of the non-highlighting, the definition of the previous ID of non-highlighting
Presect.classname = "factive";//given a non-highlighted class
var nowsect = document.getElementById (' Sect ' + ID); The current ID is highlighted, defining the current ID
Nowsect.classname = "active";//giving the highlighted class
id = ID;//assigning the current ID to the ID
}
}
HTML code
< Ul>
<li id= ' Sect0 ' class= ' active ' onclick= ' myselct (0) ' > Nuclear island </li>
<li id= ' Sect1 ' onclick= ' MYSELCT (1) ' > Regular island </li>
<li id= ' Sect2 ' onclick= ' MYSELCT (2) ' > Cooling tower </li>
<li id= ' Sect3 ' Onclick= ' MYSELCT (3) ' > Pump room </li>
<li id= ' Sect4 ' onclick= ' MYSELCT (4) ' >BOP</li>
<li id= ' Sect5 ' onclick= ' MYSELCT (5) ' > Pipelines </li>
</ul>

7,
//Remove duplicate elements in the array
function unique (arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {//loop array br> if (Result.indexof (arr[i]) = =-1) {//search for the same match
Result.push (Arr[i]);//To input a different match into another array
}
}
return R Esult;
}

8, Toggle effect
Error:
function selecttoggle (num) {
document.getElementById (' selectdirectoroption ' + num) . onclick = function () {
if (document.getElementById (' directormanage ' + num). style.display = = ' None ') {
Document.g Etelementbyid (' directormanage ' + num). style.display = ' block ';
} else {
document.getElementById (' directormanage ' + num). style.display = ' none ';
}
}
}
(the first click has no effect, then the click can play a role) reason: The text first to judge the sentence, the style (Display:none) does not necessarily work (the line style is the style of JS) so the first judgment is wrong, Then return (dispaly:none)
Modify:
function Selecttoggle (num) {
document.getElementById (' selectdirectoroption ' + num) . onclick = function () {
if (document.getElementById (' directormanage ' + num). Style.display = = ' block ') {
document. getElementById (' directormanage ' + num). style.display = ' None ';
} else {
document.getElementById (' directormanage ' + num). style.display = ' block ';
}
}
}

9. Multiple objects in an array
That's right
function Selecttestmultiple (count) {
var selectmultiple = [];
for (var i = 0; i < 3; i++) {
var selectobj = {}; (correct way)
Selectobj.userid = Multipleval1[i];
Selectobj.name = Multiplearr1[i];
Selectobj.flag = count;
Selectmultiple.push (Selectobj);
}
return selectmultiple;
}
Error
function Selecttestmultiple (count) {
var selectmultiple = [];
var selectobj = {}; (Wrong way)
for (var i = 0; i < 3; i++) {
Selectobj.userid = Multipleval1[i];
Selectobj.name = Multiplearr1[i];
Selectobj.flag = count;
Selectmultiple.push (Selectobj);
}
return selectmultiple;
}

10. The following code will output what to the console, why:
var hero = {
_name: ' John Doe ',
Getsecretidentity:function () {
return this._name;
}
};

var stolesecretidentity = hero.getsecretidentity;

Console.log (Stolesecretidentity ());
Console.log (Hero.getsecretidentity ());
What's wrong with the code and how it should be repaired.

The code will output:
Undefined John Doe
The first console.log output undefined because we are extracting the method from the Hero object,
Therefore, the stolesecretidentity () of the global context (that is, the Window object) is called, and the _name property does not exist in this global context.

11. Convert the time format into YYYY-MM-DD
YYYY-MM-DD Time Format Conversion
Date.prototype.Format = function (FMT) {//author:meizz
var o = {
"m+": This.getmonth () + 1,//month
"D+": this.getdate (),//day
"H +": this.gethours (),//hour
"m+": this.getminutes (),//min
"S+": This.getseconds (),//sec
"q+": Math.floor ((This.getmonth () + 3)/3),//Quarterly
"S": this.getmilliseconds ()//MS
};
if (/(y+)/.test (FMT)) FMT = Fmt.replace (regexp.$1, (this.getfullyear () + ""). substr (4-regexp.$1.length));
For (var k in O)
if (New RegExp ("(" + K + ")"). Test (FMT)) FMT = Fmt.replace (regexp.$1, (regexp.$1.length = = 1)? (O[k]): (("XX" + o[k]). substr (("" + O[k]).));
return FMT;
}

var date = new Date (). Format ("Yyyy-mm-dd"); \ \

12.JS Press ENTER to implement the method of login
<body onkeydown = "On_return ();" ></body>
function On_return () {
if (Window.event.keyCode = = 13) {
document.all (' login_btn '). Click ();
}
}

13. Inline and side-by-side bug
//Initial research site content block
function scgeduleadress (address, infoarrschedule) {
var Html = "";
HTML + = "<div class= ' project_group schedule_echart clearfix ' >"
Html + = "<div class= ' form_group fl ' >< Span class= ' item_info_name ' > site: </span><span class= ' Item_info maxlen_limit ' > + address + ' </span ></div> ";
Html + = "<div class= ' form_group fl ' >";
Html + = "<span class= ' item_info fl ' > Work Progress </span><span class= ' Item_info progress_value fl ' >" + Infoarrschedule + "%</span><div class= ' fl loader loader4 duration-2s-after leader_schedule_left ' ><a href= ' javascript:; ' > "+ infoarrschedule +"%</a></div> ";
Html + = "</div> (here is a </div> so the content is not wrapped, the generation of new content blocks constantly embedded, rather than side-by-side relationship, add a </div> can solve the problem)";
return Html;
}

14. Closure function
var name = "the window";
var object = {
Name: "My Object",
Getnamefunc:function () {
return function () {
return this.name;

};
}
};
Alert (Object.getnamefunc () ()); The Window
Note: 1. The child object looks up the variables for all the parent objects first-level. Therefore, all variables of the parent object are visible to the child object, and vice versa.
2. The var keyword is not used in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and this

The anonymous function itself is also a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

15. Set checked= "checked" invalid, radio unchecked!
<div class= "Form_group radio_leader_h fl" >
<label for= "" class= "Label_name" ><input type= "Radio" value= "" class= "Number_radio" name= "Visible1" id= " TwoProgramsEditChecked1 "checked=" > being compiled </label>
<label for= "" class= "Label_name" ><input type= "Radio" value= "" class= "Number_radio" name= "Visible1" id= " TwoProgramsEditChecked2 "checked=" > Finish compiling </label>
</div>

JS Code: document.getElementById (' twoProgramsEditChecked1 '). Checked = true; (bug: Sometimes it doesn't work)
The cause of the error: is the problem of the name setting, and some radio in the page, the change is changed to Name= "" does not appear duplicates.

A bug caused by a 16.id quotation mark
surveyhtml + = "<input type= ' text ' class= ' Choose_company" + Name + "' value= '" + Worktype + "' placeholder= '" readonly Name= ' + typenumber + "'; ' onclick= ' Selectothertoggle (alldir" + Idcname + "); ' > "; (X) Both ways will go wrong
surveyhtml + = "<input type= ' text ' class= ' Choose_company" + Name + "' value= '" + Worktype + "' placeholder= '" readonly Name= ' + Typenumber + '; ' onclick= ' Selectothertoggle (' alldir ' + idcname + "'); ' > "; X

function Selectothertoggle (namelist) {
Alert (document.getElementById (NameList));
if (document.getElementById (namelist). Style.display = = ' block ') {
document.getElementById (namelist). style.display = ' None ';
} else {
document.getElementById (namelist). style.display = ' block ';
}
}
Display error, alert (document.getElementById (namelist)), popup null, ID not obtained
Bug Answer: document.getElementById (namelist) inside the value of NameList is required to quote, otherwise not get the ID value (similar to document.getElementById (' name ') So in the document should be added the escape character Fu Di quotation marks (\ "), only double quotation marks will be error, so modified to
surveyhtml + = "<input type= ' text ' class= ' Choose_company" + Name + "' value= '" + Worktype + "' placeholder= '" readonly Name= ' + Typenumber + '; ' onclick= ' Selectothertoggle (\ "Alldir" + idcname + "\"); ' > ";

The parameter of function in 17.js is an array, how to pass the parameter
Bug Answer: Direct Pass the participant error, show Selectdirectorid (1, "Setnameengsurvey", collect capital, topographic measurement (surface), topographic survey (line), borehole lofting, section measurement, "-", this); it becomes a variable parameter;
The correct reference should be Selectdirectorid (1, "Setnameengsurvey", ["capital", "topographic survey (Polygon)", "topographic Survey (line)", "Borehole lofting", "Sectional Measurement"], "-", this);
So:
1. The first method can not be transmitted directly, need to pass the fun ([[[Three]]), if the direct transmission [three-way], for JS is equivalent to the arguments array directly assigned to [three-way], then passed is not an array, is a separate three parameters
2. Put menu= ["collect", "topographic survey (Polygon)", "topographic Survey (line)", "Borehole lofting", "cross section Measurement"]; become JSON data and send it in again.
var Engineermenujson = json.stringfy (menu);
surveyhtml + = "<li value=" + (k + 1) + "' onclick = ' Selectdirectorid (" + count + ", \" "+ Name +" \ "," + engineermen Ujson + ", \" "+ units +" \ ", this); ' > "+ engineermenu[k" + "</li>";

18. Determine the Type= "radio" of input
JS to determine whether checked is selected, with id.checked = True/false;
Whether the checked in HTML is selected by removing "checked" and adding "checked" to judge;

19. When you interact with Ajax data, the data submitted in JSON format can be considered as Xhr.setrequestheader ("Content-type", "application/") when there is no error while returning 415. X-www-form-urlencoded "), whether it is a JSON-formatted Xhr.setrequestheader (" Content-type "," Application/json ");

Links (https://www.cnblogs.com/SamWeb/p/6211134.html)

The data in JSON format is
var editstagealldate = {}; Create an Object
Editstagealldate.nuclearplantsid = Nuclearplantscount; Nuclear Power Plant ID
Editstagealldate.stagenumber = Createstagecount; At the stage
Editstagealldate.projectname = Createprojectname; Project name
Editstagealldate.projectnumber = Createprojectnumber; Project number
Editstagealldate.commencementdate = commencementdate; Start time
Editstagealldate.actualizationdept = actualizationdept; Implementation Unit
var Editstagealldatejson = json.stringify (editstagealldate);
alert (Editstagealldatejson);
Xhr.send (Editstagealldatejson);


20.ajax Commit Data truncated problem
Recently done a blog publishing program, using AJAX to submit data to the background, found that data is always truncated, the web search for some information, the culprit is the special character escapes after the & Trouble, now will be the solution to record, for later check

Get Data:

var data=ckeditor.getdata ();

Method one, coded with encodeURIComponent

Data=encodeuricomponent (data);
Mode two, Ajax form verification

data=$ ("#from"). Serialize ();
Ajax submissions are as follows

Copy Code
Data= "param=" +data;
$.ajax ({
Type: "POST",
URL: "Test",
data:data,////if a string containing & characters is incorrect
Success:function (str) {
......
}
});
Copy Code
Method Three, use {"": ""} to combine data

Copy Code
$.ajax ({
Type: "POST",
URL: "Test",
data:{"param":d ata},//Use this method to submit an issue that avoids data truncation caused by special characters in a string
Success:function (str) {
......
}
});
Copy Code

21. With regard to the call method in JavaScript, some information on the Web is always not detailed. To summarize the online view, call has two magical properties:

1: Inheritance. (Not too fond of this way of inheriting.) )

2: Modify the This pointer when the function is run.

var func1 = function (Arg1, arg2) {};
Through Func1.call (this, arg1, arg2);
Or func1.apply (this, [Arg1, arg2]); To invoke

Call needs to pass the parameters in order, and apply is to put the parameters in the array.
In JavaScript, the number of arguments to a function is not fixed, so if you want to say the applicable conditions,
When your parameter is explicitly known, use call, and when unsure, use apply, and then pass the parameter push into the array.

22.<iframe> tags can embed another page in the Div of one page, such as:

<iframe src= "http://baidu.com" width= "500px" height= "500px" ></iframe>;

<object> tags are primarily used to include objects, images, audio, video, Java applets, ActiveX, PDF, and Flash,

At the same time, there is a property in the tag data, you can connect to the URL, you can replace the <iframe> tag in the page to embed a sub-page, such as:

<object data= "http://www.baidu.com" width= "500px" height= "500px" ></object>

23. Arrow function Shorthand

Traditional function writing methods are easy to understand and write, but when nested in another function, these benefits are lost.

function SayHello (name) {console.log (' Hello ', name);}
SetTimeout (function () {console.log (' Loaded ')}, 2000);
List.foreach (function (item) {Console.log (item);});
Shorthand:
SayHello = name = Console.log (' Hello ', name);
SetTimeout (() = Console.log (' Loaded '), 2000);
List.foreach (item = Console.log (item));

The recent JS note, is to be able to see more than previously did not understand the place

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.