Introduce

The main record of some usual accumulation or commonly used methods or a collection of tips . In order to use in the future, but also to repeat or forget .

There is also if you encounter a good method of packaging is worth collecting . Here is mainly to record some information including JavaScript Some of the accumulation of . There's no style or page manipulation .

There may be some that you don't think are very good or can't use . If you have a better one, please correct me . Exchange and share , For your convenience , Progress together .

1. According to the file name switch attachment display picture

 /**
*@method
*@param {name} The full name of the document
*@returns Return the image address corresponding to the file type
*/
VerTypeToImage: function (name) {
var indexBegin = name.lastIndexOf(".");
var indexEnd = name.length;
var type = name.substring(indexBegin + 1, indexEnd);
switch (type) {
case "jpg":
return "/Content/images/area/NewDocument_Areas/icon_img.png";
case "word":
return "/Content/images/area/NewDocument_Areas/icon_word.png";
case "excel":
return "/Content/images/area/NewDocument_Areas/icon_excel.png";
case "ppt":
return "/Content/images/area/NewDocument_Areas/icon_ppt.png";
case "pdf":
return "/Content/images/area/NewDocument_Areas/icon_pdf.png";
case "zip":
return "/Content/images/area/NewDocument_Areas/icon_zip.png";
default:
return "/Content/images/area/NewDocument_Areas/icon_other.png";
}
}

2. According to the file type to upload files, limit specific types

 /**
*@method
*@param {name} The full name of the document
*@returns Returns whether the file type exists
*@desc turn: On behalf of the existence of running false: nonexistence
*/
VerType: function (name) {
// The collection of file types that run through
var allowtype = ["doc", "docx", "xls", "xls", , "pdf", "ppt", "pptx", "zip", "jpg", "png", "jpeg", "bmp", "gif"]
var thisfiletype = name.substring(name.lastIndexOf(".") + 1, name.length).toLowerCase();
if (allowtype.inArray(thisfiletype) == -1) {
console.log(" There is no return ")
return false;
} else {
console.log(" There is returned ")
return true;
}
}

3. Array extension determines whether a specified value exists

 Array.prototype.inArray = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};

4. Array extension to delete the specified value

 // Extended array delete 
Array.prototype.indexOf = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
}; Array.prototype.remove = function (val) {
var index = this.indexOf(val[0]);
if (index > -1) {
this.splice(index, 1);
}
};

5. Array extension does not allow adding duplicate elements

// rewrite Array Medium pushDistinct Method , Add elements to an array that do not have duplicate values 
Array.prototype.pushDistinct = function (val) {
var index = this.indexOf(val);
if (index == -1) {
this.push(val);
}
};

6. Bubble sort

 /**
*@method
*@param {data} To sort an array
*@returns Return sorted array
*/
bubble: function(data) {
for (i = 0; i < data.length - 1; i++) {
for (j = i + 1; j < data.length; j++) {
var nowValue = data[i];
if (parseInt(nowValue) > parseInt(data[j])) {
var nextValue = data[j];
data[j] = nowValue;
data[i] = nextValue;
}
}
}
return data;
}

7. recursive

 /**
*@method
*@param {n} An array
*@returns Return from 1-n And
*/
function sum(n) {
return sum(n - 1) + n;
}

8. Cross-domain request jsonp

 /**
*@method Cross-domain request jsonp
*@param {url} Request address
*@param {data} Request parameters
*@param {func} Callback function
* */
function(url, data, func) {
$.ajax({
url: url,
dataType: "jsonp",
jsonp: "callback", // It needs to be corresponding to the method of server fallback
cache: false,
data: data,
success: function(data) {
func(data);
}
});
}

9. Native js request

 /**
*@method Native js request
*@param {type} Request type get post
*@param {url} Request address
*@param {data} Request data
*@param {funSusses} Successful callback
*@param {funFailure} Failed callback
*@returns Return from 1-n And
*/
function(type, url, data, funSusses, funFailure) {
//1. establish xhr object
var xhr = null;
if(window.XMLHttpRequest) {
// Standard browser
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
};
//2. Prepare parameters before sending
xhr.open(type, url, true);
//3. Perform the send action
if(type == "get") {
xhr.send(null);
} else if(type == "post") {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
};
// Step four : Specify the callback function
xhr.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
funSusses(xhr.responseText)
} else {
funFailure(xhr.responseText)
}
}
}; }

10. Browser version determination

This is a collection version from the Internet , There are a lot of copies

<script language="JavaScript">
<!--
function getOs()
{
var OsObject = "";
if(navigator.userAgent.indexOf("MSIE")>) {
return "MSIE";
}
if(isFirefox=navigator.userAgent.indexOf("Firefox")>){
return "Firefox";
}
if(isSafari=navigator.userAgent.indexOf("Safari")>) {
return "Safari";
}
if(isCamino=navigator.userAgent.indexOf("Camino")>){
return "Camino";
}
if(isMozilla=navigator.userAgent.indexOf("Gecko/")>){
return "Gecko";
} }
alert(" Your browser type is :"+getOs());
-->
</script>

【JavaScript】 Encapsulation of practical methods 【 Keep accumulating 】 More articles about

  1. javascript Code practical method implementation

    javascript Code practical method implementation   Now we are developing , Will write some repetitive js Processing code , Today, we summarize several commonly used methods to realize . obtain get Request parameters . Go to string space .   1. obtain get Parameters in the request   ...

  2. Pick up ----javascript Some practical methods

    1. join() join() Method is used to put all elements in an array into a string . The elements are separated by the specified separator . var ids = [];                 for(var i = 0 ...

  3. JavaScript Encapsulating a function works like a built-in method concat()

    JavaScript Encapsulating a function works like a built-in method concat() First of all, recall concat() The role of : concat() Method to connect two or more arrays . This method does not change the existing array , Only one of the connected arrays is returned ...

  4. JavaScript Common debugging methods

    Editor's Guide :javascript Debugging method , Common use alert and console To locate the error and whether the output result is desired , stay chrome in , You can also use breakpoints to see the running situation, etc , This paper introduces a more comprehensive debugging method , You know, co ...

  5. JavaScript Summary of string practical operation

    JavaScript Strings are used to store and process text . So I'm writing JS She's always with me when I code , When you process user input data , In reading or setting DOM Object's properties , In operation Cookie when , In the transformation of all kinds of different Da ...

  6. Use jQuery Encapsulating utility functions

    One . introduction Project under development , The front end will have a helper class js file , such as cookie The operation of , Team members encapsulate their own methods . Most of the time , We developers write a global function ourselves , Regardless of the later maintenance personnel will write the same code , And then create the code ...

  7. JavaScript encapsulation

    js Encapsulation is to simplify the use of , Internal logic and usage are decoupled . The user only needs to know the parameters and return values , Others don't need to use personnel settings . Encapsulation is to encapsulate attributes , Method , Fields are encapsulated into classes . JavaScript Encapsulation method 1, Function mode func ...

  8. javaScript Various ways of writing encapsulation

    stay javascript In the world of , Writing is a magical phenomenon , It's a hundred families opening up ! Every time I see what foreigners write js Components , Thought and writing are weird , I didn't see one js Code with basically the same structure . today , I'll talk about it js How to write it , I'm in the process of developing , Also write ...

  9. image jQuery like that , Using the chain approach , Encapsulate a method :CSS()

    The main idea is : return this object , Put the obtained operation elements into an array . Add extension methods to the prototype <html> <head> <title></title> &l ...

Random recommendation

  1. OC Inheriting subclass objects to call method mechanism Subclass objects access instance variables in the parent class

    In inheritance , How subclass objects call the right method every last Objective - C Objects have a hidden pointer to the code of the class , When sending a message to an object , The current object will first find the corresponding method in the current class , If you find it , straight ...

  2. session There are three ways to handle timeouts

    1.       stay web Set... In the container ( Here to tomcat For example ) stay tomcat-5.0.28\conf\web.xml Set in , Here are tomcat 5.0 Default configuration in : <!-- ========= ...

  3. turn : mysql create view Create view

    The following article is mainly about MySQL Description of the view , These include MySQ View L summary , And how to create MySQL View -create view And modification MySQL View --alter view And so on , The following is the specific content of the article ...

  4. 【WebStorm】 Front end tool development tool webstrom Special article ... Updating

    http://my.oschina.net/maomi/blog/137807#OSC_h2_5 WebStorm Mashup svn WebStorm Mashup nodeJS webstorm Brief introduction webstor ...

  5. 9.Linux System guidance process

    One .Linux System guidance process When we press the power button of the host, it starts , On the main board CMOS/BIOS The module will perform a firmware self test , To check that the hardware is properly connected . stay Linux In the guidance process , Generally, it can be divided into the following main processes : 1. ...

  6. A good team leader Some qualities we should have

    First , Good technology . After all, a team is relying on technology to create value for others , a certain extent , The team leader The technical ability of the whole team determines the technical limit .leader The persistence and pursuit of technology may affect the team members' persistence and pursuit of technology , At least le ...

  7. MapReduce-TextInputFormat Slicing mechanism

    MapReduce By default  TextInputFormat Slice , The mechanism is as follows (1) Simply slice according to the content length of the file (2) Slice size , Default equal to Block size , It can be set separately (3) Slice without considering the data set ...

  8. sql In the query list table, it is greater than 2 Data for

    SELECT COUNT( Field )AS COUNT, Field FROM Table name GROUP BY Field HAVING COUNT >=

  9. use JavaDoc Generate project documentation

    It's the end of the project , Everybody's starting to have a headache —— It's time to document again …… Yes , Most of us are not from the formal Programer Trained . When I learned to program , I never thought of writing a complete document for the programs I wrote , All the comments are ...

  10. [ Microsoft ]The latest version of Windows is Windows Sandbox

    The latest version of Windows is Windows Sandbox by Surur @mspoweruser Dec 19, 2018 at 1:40 GMT As h ...