如何在JavaScript/jQuery中将特定名称映射到ID



问题:我想遍历一组特定的名称属性,并将这些值附加到特定的ID中。

我有一个演示,试图读取用户输入,右侧的文本将分别得到镜像。

目前,我在特定的名称属性中进行迭代。然而,我现在想将其附加到右侧的一个相应的文本框中。它是附加到所有四个元素。

如何映射这些元素?

$('input[name^="text"]').on("change", function(e){
var user_input = $(this).val();
console.log(user_input);
$('input[id^="id_text"').each(function() {
let mirrored_value = $(this).val(user_input);
});
});
body {
padding:10px;
}
input {
margin: 20px 0 0 0;
}
.mirror{
float: left;
margin-left: 20px;
}
.input{
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> The right text box will mirror the left</h1>
<div class="input">
<input type="text" name="text1" value=""><br>
<input type="text" name="text2" value=""><br>
<input type="text" name="text3" value=""><br>
<input type="text" name="text4" value=""><br>
</div>
<div class="mirror">
<input type="text" id="id_text1" value=""><br>
<input type="text" id="id_text2" value=""><br>
<input type="text" id="id_text3" value=""><br>
<input type="text" id="id_text4" value="">
</div>

我的首选方法是使用引用目标元素并引用该元素的数据属性。这样,如果您更改标记,就不必担心更改javascript。此外,input事件是文本输入的更好选项。

$('input[data-target]').on("input", function(e){
$($(this).data("target")).val($(this).val());
});
body {
padding:10px;
}
input {
margin: 20px 0 0 0;
}
.mirror{
float: left;
margin-left: 20px;
}
.input{
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> The right text box will mirror the left</h1>
<div class="input">
<input data-target="#id_text1" type="text" name="text1" value=""><br>
<input data-target="#id_text2" type="text" name="text2" value=""><br>
<input data-target="#id_text3" type="text" name="text3" value=""><br>
<input data-target="#id_text4" type="text" name="text4" value=""><br>
</div>
<div class="mirror">
<input type="text" id="id_text1" value=""><br>
<input type="text" id="id_text2" value=""><br>
<input type="text" id="id_text3" value=""><br>
<input type="text" id="id_text4" value="">
</div>

使用闭包并假设<input>元素组的顺序相同:

const $src = $('.input > input');
const $dst = $('.mirror > input');
$src.each((i,e) => {
const $mirror = $dst.eq(i);
$(e).on('change', e => {
let user_input = $(e.currentTarget).val();
console.log(user_input);
$mirror.val(user_input);
});
});

如果标记始终可靠,我会使用索引。不需要ID或其他属性。

$('.input input').on("keyup", function(e){
const idx = $(this).index();
const val = $(this).val();
$('.mirror input').eq(idx).val(val);
});
.input, .mirror {display: inline-block; width: 45%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> The right text box will mirror the left</h1>
<div class="input">
<input type="text" name="text1" value="">
<input type="text" name="text2" value="">
<input type="text" name="text3" value="">
<input type="text" name="text4" value="">
</div>
<div class="mirror">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
</div>

最新更新