0

私はjavascriptライブラリを書いています。基本的なコードは次のとおりです。

(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);

body セクションには、入力と id を持つ div がありtestます。入力ボタンにこれがあります: onclick=tex('#test').dit();. コードを実行しようとすると、未定義であるというエラーが表示されます。私のコードの何が問題なのか誰か知っていますか?

4

1 に答える 1

1

document.getElementById は、「#」なしで要素自体の ID のみを受け入れます。ハッシュ表記は jquery と css で ID を示すために使用されますが、要素自体をターゲットにするには、ID (この場合は「test」) を使用するだけです。

スクリプトを実行するには、「.」を削除する必要があります。getElementById または getElementByClass をそれぞれ呼び出す前に、または「#」を使用してください。

これを実現するには、javascript substringメソッドを使用できます。

編集: return ステートメントを持たない関数 .tex に関する Pointy のコメントも参照してください。

于 2013-10-11T12:47:39.527 に答える