更改具有相同 id 的输入类型的所有值

Change all values of input types with same id

我现在遇到的问题是我想更改 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/

不幸的是 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();

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.

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

当您使用 id 选择器时,它将 return 只有与 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" />

使用以下代码使用 ID 属性设置字段值

$(document).ready(function() {
$("[id='second']").each(function(){
      $(this).val('test');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<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" />