2015-04-01 51 views
1

我目前得到的是一个问题,我想要更改id与输入类型匹配的每个元素值。请看看我的jsFiddle,这应该为你清理很多。问题是值不会改变所有输入类型,它只会改变该ID的第一个输入类型。尝试使用.each函数,但没有帮助。更改具有相同编号的输入类型的所有值

HTML

<input type="text" id="first" value="tesdafsdf" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 

jQuery的

$('#first').keyup(function() { 
    updateSearch(); 
}); 

var updateSearch = function() { 
    $('#second').each(function(index, value) { 
     this.value = $('#first').val(); 
    }); 
}; 

//Change the values for testing purpose 
updateSearch(); 

http://jsfiddle.net/ZLr9N/377/

+3

ID必须是相同的..使用类 – 2015-04-01 09:51:58

+0

@ArunPJohny等待什么实际工作,你们能不能进一步elleborate这是为什么?这对我来说毫无意义。 – Jordy 2015-04-01 09:53:24

+0

这有一些解释** [Id必须是唯一的](http://programmers.stackexchange.com/a/127180)** – 2015-04-01 09:55:07

回答

7

ID被用于唯一地标识一个元件,使得元件的ID必须独一无二

它在文档中必须是唯一的,并且通常用于使用getElementById检索 元素。 ID的其他常见用法包括使用 元素的ID as a selector在使用CSS对文档进行样式设置时。

当你必须对多个元素进行分组时,最简单的方法之一就是使用class属性。

当你使用一个id选择器时,它只会返回与ID匹配的第一个元素其余元素将被忽略。

所以元素的

$('.first').keyup(function() { 
 
    updateSearch(); 
 
}); 
 

 
var updateSearch = function() { 
 
    $('.second').val($('.first').val()); 
 
}; 
 

 
//Change the values for testing purpose 
 
updateSearch();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="first" value="tesdafsdf" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" />

+0

我想非常感谢您的意见,这是有价值的信息,并会真正帮助我改进!我需要等待8分钟才能接受你的答案。 – Jordy 2015-04-01 09:58:16

3

不幸的是HTML元素的ID的需要是不同的,他们是为了是唯一的标识符。类然而可以应用于多个元素,像这样:

HTML

<input type="text" id="first" value="tesdafsdf" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 

的Javascript

$('#first').keyup(function() { 
    updateSearch(); 
}); 

var updateSearch = function() { 
    $('.second').each(function(index, value) { 
     this.value = $('#first').val(); 
    }); 
}; 

//Change the values for testing purpose 
updateSearch(); 
+3

为什么“不幸”? :P – nicael 2015-04-01 09:56:24

+0

从来不知道这一点甚至在js/jquery/html中非常重要,感谢您为我清除它! – Jordy 2015-04-01 09:59:17