javascript - 如何强制输入集合在输入时始终具有相同的值?
问题描述
我正在寻找一种方法,当我在输入集合上输入内容时,给输入集合赋予相同的值,假设我们有 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>
解决方案
在我的脑海中,我会这样做,但是我有一段时间没有写 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>
推荐阅读
- javascript - 按给定的数字序列对 Javascript 数组进行排序
- c# - LINQ:选择表中每分钟的第一个值
- android - bottomsheetbehaviour 的生命周期事件是什么?
- python - 在python中解压缩压缩数据的代码?
- c# - Dynamics 365 CRM SDK 或 Rest API
- python - 使用 Scrapy 和 Xpath 检索完整的 url
- python - Django admin inline - 仅在更改对象时显示
- python-3.x - 我对这段代码感到困惑,有人可以解释一下吗
- node.js - 未找到本地 Npm 模块“jshint-stylish”。安装了吗?
- python-3.x - _pickle.UnpicklingError:无效的加载键,'H'