Home >Web Front-end >JS Tutorial >Summary of commonly used JavaScript scripts (2)_javascript skills

Summary of commonly used JavaScript scripts (2)_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:11:071288browse

Convert pseudo array in JavaScript to real array

In JavaScript, the hidden variable arguments in the function and the element collection (NodeList) obtained with getElementsByTagName are not real arrays. Methods such as push cannot be used. When necessary, they can only be converted to real arrays first. .

For arguments, you can use Array.prototype.slice.call(arguments); to achieve the purpose of conversion, but this is not possible for NodeList. It will report an error in IE8 and below. It can only be said that its JS engine has limitations. .

Therefore, if you need to convert NodeList into a real array, you need to do compatibility processing.

Copy code The code is as follows:

function realArray(c) {
Try {
         return Array.prototype.slice.call(c);
} catch (e) {
var ret = [], i = 0, len = c.length;
for (; i < len; i ) {
             ret[i] = (c[i]);
}
         return ret;
}
}

JavaScript setting homepage function

Copy code The code is as follows:




JavaScript settings "Set as homepage" and "Favorite page" (compatible with IE and Firefox browsers)




Set as homepage


JavaScript collection function

Copy code The code is as follows:




    demo
   
   
   
   


    收藏本站

 

基于JQuery的,你可以根据自己的需求来修改。

javascript检测元素是否支持某个属性代码

复制代码 代码如下:

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

用法:

复制代码 代码如下:

if (elementSupportsAttribute("textarea", "placeholder") {
} else {
   // fallback
}

创建和使用命名空间

复制代码 代码如下:

var GLOBAL = {};
GLOBAL.namespace = function(str){
var arr = str.split('.'),o = GLOBAL;
for(k=(arr[0]=="GLOBAL")?1:0;k     o[arr[k]]=o[arr[k]]||{};
    o=o[arr[k]];
    }
}

使用方式

复制代码 代码如下:

GLOBAL.namespace("Lang");
GLOBAL.Lang.test = function(){
    //todo
}

以上就是本文的全部内容了,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn