2011-04-08 79 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。 (我找不到任何强制类型的方法)。

感谢您的帮助! :)