首页 > 解决方案 > 如何强制输入集合在输入时始终具有相同的值?

问题描述

我正在寻找一种方法,当我在输入集合上输入内容时,给输入集合赋予相同的值,假设我们有 10 个输入,然后我在其中一个输入“狗”这个词,然后所有输入都得到“狗”这个词,然后我给另一个人输入“猫”这个词,每个人都得到“猫”这个词。

像这样的东西,这是无效的,但我只是想解释一下逻辑:

$(document).on('input', 'input', function () {

$("#main input").each(function() {

$(this).val($(this).val())

});

});

有任何想法吗?

input{
position:relative;
float:left;
clear:both;
margin-bottom:1px;
width:85px;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="main">
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
</div>
</body>
</html>

标签: javascripthtmljquery

解决方案


在我的脑海中,我会这样做,但是我有一段时间没有写 jQuery 了。

因为我假设您可能在页面上有其他输入字段,所以我创建了一个数据属性,称为data-copy附加我们的事件侦听器。我不倾向于通过一个完全有效的类来做到这一点,主要是因为它太容易将样式附加到这些类,然后混合功能和样式。在此处阅读有关属性选择器的更多信息:https ://api.jquery.com/category/selectors/attribute-selectors/

如果您想在没有属性的情况下执行此操作,您可以将选择器更改为类似的内容,但我会提醒您使其具体化以避免副作用。

$(function() {
  $('#main input').on('keyup', function() {
    const val = $(this).val();
    $('#main input').not(this).val(val);
  });
});

$(function() {
  $('[data-copy]').on('keyup', function() {
    const val = $(this).val();
    $('[data-copy]').not(this).val(val);
  });
});
input {
  position: relative;
  float: left;
  clear: both;
  margin-bottom: 1px;
  width: 85px;
  text-align: center;
}
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
  <div id="main">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
    <input data-copy type="text">
  </div>
</body>
</html>


推荐阅读