В то время как вы уже приняли ответ, я хотел бы предложить это альтернатива:
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 (в комментариях ниже):
В 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()
называть напрямую, а не (как описано выше), имеющих трепать использовать две вызовы функций в unsupporting браузерах (и тестирования для его существования каждый раз), чтобы успешно использовать один функцию.
Спасибо! Оно работает! – Crys
Ты очень рад; Я рад, что помог вам :) –
В 'var input = document.getElementsByTagName ('input')' i не могу поместить элемент по id, а не по имени тега? Потому что я хочу получать контент только из определенных полей, например из textarea. – Crys