Jor*_*rdy 1 javascript jquery dom
我现在得到的是一个问题,我想改变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" />
Run Code Online (Sandbox Code Playgroud)
jQuery的
$('#first').keyup(function() {
updateSearch();
});
var updateSearch = function() {
$('#second').each(function(index, value) {
this.value = $('#first').val();
});
};
//Change the values for testing purpose
updateSearch();
Run Code Online (Sandbox Code Playgroud)
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();Run Code Online (Sandbox Code Playgroud)
<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" />Run Code Online (Sandbox Code Playgroud)