javascript - 一事件触发一类一id jQuery
问题描述
通过同一次单击,我需要在两个不同的字段中添加两个不同的值:value 和 value*50。因此,我试图通过类获取一个字段,而通过 ID 获取另一个字段。由于某种原因,它不起作用。这是我正在使用的逻辑。有人可以启发我吗?
</script>
<script type="text/javascript">
$('button').on('click', function() {
let value = this.value;
$($(this).data('target')).val(value*50).trigger('input');
});
$('button').on('click', function() {
let value = this.value;
$($(this).attr('id')).val(value).trigger('input');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="bedroom" data-target=".i1" value="1">1</button>
<input type="text" class="i1" id="i1" name="i1"><br>
<input type="text" id="bedroom">
解决方案
You can't have multiple elements with the same ID. Also you don't need to write 2 click events for the same button.
$('button').on('click', function() {
let value = this.value;
$($(this).data('target')).val(value * 50).trigger('input');
$("." + $(this).attr('id')).val(value).trigger('input');
});
Demo
$('button').on('click', function() {
let value = this.value;
$($(this).data('target')).val(value * 50).trigger('input');
$("." + $(this).attr('id')).val(value).trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="bedroom" data-target=".i1" value="1">1</button>
<input type="text" class="i1" id="i1" name="i1"><br>
<input type="text" class="bedroom">
推荐阅读
- angular - 如何在角度材质对话框中创建自定义动画?
- r - 使用地图功能从谷歌趋势数据创建数据框
- python - 强制 ayncio 协程启动
- python - python win32print 无法设置自定义页面大小
- docker - 使用 docker-compose 并启动容器,但其中一个容器无法连接到其他容器
- javascript - 删除一个具有相同键的文档后,如何通过使用 Mongoose 的 deleteOne 方法和键来获取错误?
- java - 无限循环的单元测试用例
- html - 使用 ajax 上传文件并使用 java servlet 服务器端处理它
- python - 在 python 中使用 glob.glob 从 pc 返回路径时获取空列表
- python - 如何让熊猫将空数据文件作为空数据框读取?