[英]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();
ID用于唯一标识元素,因此元素的ID必须唯一 。
它在文档中必须唯一,并且通常用于使用getElementById检索元素。 id的其他常见用法包括在使用CSS设置文档样式时使用元素的ID作为选择器 。
当您必须对多个元素进行分组时,最简单的方法之一就是使用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" />
不幸的是,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" />
Java脚本
$('#first').keyup(function() {
updateSearch();
});
var updateSearch = function() {
$('.second').each(function(index, value) {
this.value = $('#first').val();
});
};
//Change the values for testing purpose
updateSearch();
使用以下代码通过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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.