首页 > 解决方案 > 一事件触发一类一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">

标签: javascriptjquery

解决方案


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">


推荐阅读