簡體   English   中英

Javascript庫未定義

[英]Javascript library undefined

我正在寫一個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);

在主體部分,我有一個輸入和一個帶id test的div。 在輸入按鈕上,我有: onclick=tex('#test').dit(); 當我嘗試運行代碼時,出現錯誤消息,提示未定義。 有人知道我的代碼有什么問題嗎?

document.getElementById僅接受元素本身的ID,而不包含“#”。 在jquery和css中使用哈希表示法來表示id,但僅使用id來定位元素本身即可,在這種情況下為“ test”。

要運行腳本,您需要刪除“。” 或“#”,然后分別調用getElementById或getElementByClass。

您可以使用javascript 子字符串方法來實現此目的。

編輯:也請參考Pointy對函數.tex的注釋,該注釋沒有return語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM