为所有目标元素调用 java 脚本函数
Call a java script function for all targeted elements
我找到了一个 javascript function,我想将其应用于所有目标元素,在我的例子中是页面中的所有文本区域,但是当我将选择器从 document.getElementById('text');
更改为 document.querySelectorAll('textarea');
或document.getElementsByTagName('textarea')
为了定位所有元素不起作用,我不明白为什么,我尝试将 text
变量放入 for
但仍然不起作用,如果有人可以帮助我关于这个虚拟问题的一点点:|
你在循环的正确轨道上,你只是走得不够远(见评论):
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);
}
}
我找到了一个 javascript function,我想将其应用于所有目标元素,在我的例子中是页面中的所有文本区域,但是当我将选择器从 document.getElementById('text');
更改为 document.querySelectorAll('textarea');
或document.getElementsByTagName('textarea')
为了定位所有元素不起作用,我不明白为什么,我尝试将 text
变量放入 for
但仍然不起作用,如果有人可以帮助我关于这个虚拟问题的一点点:|
你在循环的正确轨道上,你只是走得不够远(见评论):
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);
}
}