简体   繁体   中英

Javascript library undefined

I am writing a javascript library. here is the basic code:

(function (window) {
        var versrionInfo = {
            release : 1.0,
            date : "10/5/2013",
            releaseNotes : "This is the first oficial release of techx. Basic functions have been implemented."
        },
        regex = {
            Id : /^[#]\w+$/,
            Class : /^[.]\w+$/,     
            Tag : /^\w+$/,
            validSelector : /^([#]\w+|[.]\w+|\w+)$/
        },  
        tex = function(selector){
            //only some of the functions need to select an element
            //EX:
            // style: tex(selector).style(style);
            //one that would not need a selector is the random number function:
            // tex().random(from,to);
            if (selector){
                if (typeof selector === 'string'){
                    var valid = regex.validSelector.test(selector);
                    if( valid ){
                        this.length = 1;
                        if(regex.Id.test(selector)){ 
                            this[0] = document.getElementById(selector);
                        }
                        if(regex.Class.test(selector)){ 
                            this[0] = document.getElementByClass(selector);
                        }
                        if(regex.Tag.test(selector)){ 
                            this[0] = document.getElementByTagName(selector);
                        }
                    }
                }else if(typeof selector === 'object'){
                    this = selector;
                }
                //this = document.querySelector(selector);
                // I could make a selector engine byt I only need basic css selectors.
            }
        };
        tex.prototype = {
            dit : function(){
                this.innerHTML = 'Hi?!?!?!';
            }
        };
        window.tex = tex;
})(window);

In the body section I have an input and a div with the id test . On the input button I have this: onclick=tex('#test').dit(); . When I try to run the code I get an error that says it is undefined. Does anyone know what is wrong with my code?

document.getElementById accepts only the id of the element itself without '#'. The hash notation is used in jquery and css to indicate an id but to target the element itself you just use the id - in this case 'test'.

To make your script run you need to remove the '.' or '#' before you call getElementById or getElementByClass respectively.

You could use the javascript substring method to achieve this.

Edit: Also refer to Pointy's comment on the function .tex not having a return statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM