我现在遇到的问题是我想更改 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();
最佳答案
ID用于唯一标识元素,因此元素的 ID 必须是唯一的。
It must be unique in a document, and is often used to retrieve the element using getElementById. Other common usages of id include using the element's ID as a selector when styling the document with CSS.
当您必须对多个元素进行分组时,最简单的方法之一是使用类属性。
当您使用 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" />
关于javascript - 更改具有相同 id 的输入类型的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29387657/