2011-04-08 128 views
2

我有一個JS功能選擇基於參數連續JS方法

function getElement() { 
    var scope = document; 

    this.by = function(data) { 
     for (key in data) { 
      if (key == 'id') scope = scope.getElementById(data.id); 
      if (key == 'tag') scope = scope.getElementsByTagName(data.tag); 
     }  
     return scope; 
    } 
} 

function getEl(data) { return new getElement().by(data); } 

這就是所謂的喜歡getEl(id : 'divId', tag : 'span'),它會在div「DIVID選擇」選擇全部跨度的一些元素。

現在,我想做另一個函數(內部函數元素),稱爲風格,將改變所有先前選定的跨度的CSS。

喜歡的東西

function getElement() { 
    var scope = document; 

    this.by = function(data) { 
     for (key in data) { 
      if (key == 'id') scope = scope.getElementById(data.id); 
      if (key == 'tag') scope = scope.getElementsByTagName(data.tag); 
     }  
     return scope; 
    } 

    this.style = function(data) { 
     console.log(data); 
    } 
} 

我希望能夠像做getEl({id : 'divId', tag : 'span').style({display : 'none'})

但是,這似乎並沒有工作,我收到一個getEl({id: "divId", tag: "span"}).style is undefined錯誤。

ps:這僅用於學習目的,請不要提示jQuery或其他此類框架! :)

親切的問候!

+1

「連續的js方法」被稱爲鏈接 – 2011-04-08 18:20:32

+0

:)謝謝!因爲你可能認爲JS對我來說很新。 – 2011-04-08 18:22:40

+0

順便說一下,'getElementById'只支持'Document'對象。它不適用於'元素'或'節點' – cem 2011-04-08 18:27:02

回答

1

getEl返回scope變量,該變量是DOM元素列表,而不是對getElement的引用。您需要返回this才能夠執行類似new getElement().by(data).style()的操作。

this.by = function(data) { 
    for (key in data) { 
     if (key == 'id') scope = scope.getElementById(data.id); 
     if (key == 'tag') scope = scope.getElementsByTagName(data.tag); 
    }  
    return this; 
} 

然後你可以做getEl({id : 'divId', tag : 'span'}).style({display : 'none'})

要獲得scope變量,您可以添加這樣的事情:

this.elements = function(){ 
    return scope; 
} 

getEl({id : 'divId', tag : 'span'}).elements()將返回DOM元素的列表。

0

我想通了,這要歸功於火箭:)

function getElement() { 
    this.scope = document; 

    this.get = function() { 
     return this.scope; 
    } 

    this.by = function(data) { 
     for (key in data) { 
      if (key == 'id') this.scope = this.scope.getElementById(data.id); 
      if (key == 'tag') this.scope = this.scope.getElementsByTagName(data.tag); 

     } 
     return this; 
    } 

    this.style = function(data) { 
     console.log(typeof(this.scope)); 
     for (key in data) { 
      if (this.scope.length) { 
       for (i = 0; i < this.scope.length; i++) { 
        this.scope[i].style[key] = data[key]; 
       } 
      } 
      else { 
       this.scope.style[key] = data[key]; 
      } 
     } 
     return this; 
    } 
} 
function getEl(data) { return new getElement().by(data); } 

它適用於: getEl({id : "tara_content", tag : "div"}).style({display : "none"}); getEl({id : "tara_content"}).style({display : "none"}); getEl({tag : "div"}).style({display : "none"});

由於馬蒂亞斯Bynens注意到by()可以返回元素的數組或一個元素,這就是爲什麼我在style()中檢查的長度爲this.scope。 (我找不到任何強制類型的方法)。

感謝您的幫助! :)