虽然您已经接受了答案,但我想建议这个替代方案:
function updateValue(els, output){
// creates an empty array
var textArray = [];
/* iterates through the `els` array and if the value is not
an empty string, splits the value at the white-spaces
and pushes the array of values to the `textArray` */
for (var i=0,len=els.length; i<len; i++){
if (els[i].value !== ''){
textArray.push(els[i].value.split(/\s/));
}
}
/* makes the value of the `output` (textarea) equal to the
comma-separated string of words from the inputs, and
adds a full-stop/period to the end of the 'sentence' */
output.value = textArray.join(',') + '.';
}
var inputs = document.getElementsByTagName('input'),
output = document.getElementById('result'),
els = [];
// makes an array from the `inputs` nodeList
for (var i = 0, len = inputs.length; i<len; i++) {
els.push(inputs[i]);
}
// assigns the function to call
for (var i = 0, len = els.length; i<len; i++) {
els[i].onkeyup = function(e){
updateValue(els, result);
};
}
JS Fiddle demo.
编辑以解决 OP 留下的问题(在 cmets 中,如下):
在var inputs = document.getElementsByTagName('input') 我不能通过id 获取元素,而不是通过标签名称?
当然可以。对于如何收集要采取行动的相关元素,您有多种选择;不过,在示例中,我只会将这些元素放入 els 变量中;因为这已经是传递给函数的那个了(但可以根据自己的代码进行调整)。
首先,使用document.getElementById():
var els = [document.getElementById('one'),document.getElementById('two')];
JS Fiddle demo(注意删除了第一个for循环,用于将相关节点推入els数组)。
其次,您可以使用一个数组来包含您想要操作的那些元素的id:
/* not every browser has access to `indexOf()` for arrays, so an
alternative is defined */
function inArray(needle,haystack) {
// use native version if possible:
if ([].indexOf !== undefined){
return haystack.indexOf(needle);
}
// otherwise use custom approach:
else {
for (var i=0,len=haystack.length; i<len; i++){
if (needle == haystack[i]){
return i;
}
}
return -1;
}
}
var inputs = document.getElementsByTagName('input'),
output = document.getElementById('result'),
// array of the `id`s of the elements you want to use:
elementIdsToUse = ['one','two'],
els = [];
for (var i = 0, len = inputs.length; i<len; i++) {
// if the `inputs[i]` node's `id` is in the array of `id`s...
if (inArray(inputs[i].id,elementIdsToUse) > -1){
// push that node to the `els` array:
els.push(inputs[i]);
}
}
for (var i = 0, len = els.length; i<len; i++) {
els[i].onkeyup = function(e){
updateValue(els, result);
};
}
JS Fiddle demo.
第三,你当然可以使用类名(同样,使用indexOf()):
for (var i = 0, len = inputs.length; i<len; i++) {
if (inputs[i].className.indexOf('useThis') > -1){
els.push(inputs[i]);
}
}
for (var i = 0, len = els.length; i<len; i++) {
els[i].onkeyup = function(e){
updateValue(els, result);
};
}
JS Fiddle demo.
最后,在改变主意之后;一种扩展 Array 原型的方法,如果当前浏览器中不存在 Array.indexOf() 方法,则提供该方法:
Array.prototype.indexOf = Array.prototype.indexOf || function(needle) {
for (var i = 0, len = this.length; i<len; i++){
if (this[i] == needle){
return i;
}
}
return -1;
};
JS Fiddle demo.
这允许直接调用Array.indexOf(),而不是(如上)在不支持的浏览器中不必要地使用两个函数调用(并测试它的存在每次) 成功使用一个功能。