Summary of JavaScript common scripts (ii)

  • 2020-05-10 17:43:11
  • OfStack

Convert the pseudo array in JavaScript to a true array

In JavaScript, both the hidden variable arguments in the function and the collection of elements obtained with getElementsByTagName (NodeList) are not real arrays, so push and other methods cannot be used, and can only be converted to real arrays first when necessary.

For arguments, can use Array. prototype. slice. call (arguments); For the purpose of conversion, but not for NodeList, which will report an error at IE8 or below, saying only that its JS engine is limited.

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


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 sets the home page function


<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Set "set as home page" and "favorite page" (compatible IE And firefox) </title>
    <meta charset="utf-8">
    <script type="text/javascript">
        function setHomepage() {
            if (document.all) {
                /*IE*/
                document.body.style.behavior = 'url(#default#homepage)';
                document.body.setHomePage(window.location.href);
            } else if (window.sidebar) {
                /*FF*/
                if (window.netscape) {
                    try {
                        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                    } catch (e) {
                        alert(" This action is rejected by the browser if you want to enable the feature , Please enter in the address bar about:config, Then put the items signed.applets.codebase_principal_support The value true");
                    }
                }
                var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                prefs.setCharPref('browser.startup.homepage', window.location.href);
            } else {
                /*chrome Or other */
                alert(" Your browser does not support automatic home page Settings , Please use the browser menu to set it manually !");
            }
        }
    </script>
</head>
<body>
    <a onclick="setHomepage()" title=" Set to the home page " href="javascript:void(0);"> Set to the home page </a>
</body>
</html>

JavaScript collection feature


<!DOCTYPE html>
<html>
<head>
    <title>demo</title>
    <meta charset="utf-8">
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript">
        jQuery.fn.addFavorite = function(l, h) {
            return this.click(function() {
                var t = jQuery(this);
                if(jQuery.browser.msie) {
                    window.external.addFavorite(h, l);
                } else if (jQuery.browser.mozilla || jQuery.browser.opera) {
                    t.attr("rel", "sidebar");
                    t.attr("title", l);
                    t.attr("href", h);
                } else {
                    alert(" Please use the Ctrl+D Add this page to your favorites! ");
                }
            });
        };
        $(function(){
            $('#fav').addFavorite(document.title,location.href);
        });
    </script>
</head>
<body>
    <a href="javascript:;" title=" Collect this site " id="fav"> Collect this site </a>
</body>
</html> 

Based on JQuery, you can modify it according to your own requirements.

javascript detects whether an element supports an attribute code


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

Usage:


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

Create and use namespaces


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

use


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

That's all for this article, I hope you enjoy it.


Related articles: