2015-05-06 32 views
0

我发现了一个javascript function,我想应用到所有目标元素,在我的情况下,从网页中的所有文本区域,但是当我为了我改变从document.getElementById('text');选择为document.querySelectorAll('textarea');document.getElementsByTagName('textarea')目标所有元素不工作,我不明白为什么,我试图把text变量在for,但仍无法正常工作,如果有人可以帮我一点点这个虚拟的问题:|调用Java脚本函数的所有目标元素

+0

所以总结:你已明白'getElementsByTagName'返回的项目列表。你已经理解你需要某种循环来一一浏览它们。你半心半意地试图使用'for'循环。你有**没有**查看任何文档或'for'循环的例子。你有**没有**尝试超过10分钟。 – Tomalak

回答

1

你在正确的轨道与一个循环,你只是没有走得足够远(见注释):

function init() { 
    var list, i, text; 

    // Get the list 
    list = document.getElementsByTagName('textarea'); 

    // Loop through it 
    for (i = 0; i < list.length; ++i) { 
     // Get this entry 
     text = list[i]; 

     // Do things with it 
     observe(text, 'change', resize); 
     observe(text, 'cut',  delayedResize); 
     observe(text, 'paste', delayedResize); 
     observe(text, 'drop', delayedResize); 
     observe(text, 'keydown', delayedResize); 

     // Initial `resize` call -- I'm using `.call` in order to 
     // set `this` to the element during the call, like an event 
     // does 
     resize.call(text); 

     // You'll have to choose *one* of them to focus; I chose the first 
     if (i == 0) { 
      text.focus(); 
      text.select(); 
     } 
    } 
    function resize() { 
     // Note that I'm using `this` here, not `text` or `list` 
     // `this` will refer to the element the event is occurring on 
     this.style.height = 'auto'; 
     this.style.height = this.scrollHeight+'px'; 
    } 

    // 0-timeout to get the already changed text 
    function delayedResize() { 
     // Again note the use of `this`, also `.bind`. 
     // `Function#bind` creates a function that, when called, 
     // calls the original with a specific `this` value 
     window.setTimeout(resize.bind(this), 0); 
    } 
} 
+0

ty帮助和你的时间! – RulerNature

+0

@ T.J。 Crowder,我们可以点击它作为jquery使用某些类名应用事件绑定的所有元素? –

+0

@openandfree:jQuery基本上对匹配的元素进行循环。如果你想找到匹配类(或任何其它CSS选择器)的元素,你可以使用'document.querySelector(“选择在这里”)'。 –