首页 > 解决方案 > 脚本的jQuery交互逻辑(主题输入被锁定)

问题描述

我有这个简单的脚本:它读取quantity输入的值,如果它大于 5,jQuery 将自动选择单选按钮 #2。如果 的值quantity小于 5,它将选择单选按钮 #1。

现在我的问题是这个脚本使单选按钮不可点击,因为它们的状态与脚本严格相关。但如果单击单选按钮#2 会将输入值更改为 5,然后单击单选按钮#1 会将其更改为 1,我会希望它。

换句话说,我希望这个脚本能够双向工作并且不锁定我的按钮。

$('.mycontainer').on('click', function() {

if (parseInt($('#quantity').val(), 10) >= '5') {
    $('#2radio').prop('checked', true);
}
	else {
	$('#1radio').prop('checked', true);
}
}).click();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="mycontainer">

  <input type="number" id="quantity" name="quantity" value="1"><br><br>
  
    <input type="radio" id="1radio" name="radio"><label for="1radio">radio button #1</label><br><br>
    <input type="radio" id="2radio" name="radio"><label for="2radio">radio button #2</label>
    
    <div>

标签: javascriptjquery

解决方案


每当您检查 aradio时,该事件就会冒泡并触发该.mycontainer功能,并且由于该值未更改,因此它会重新选择另一个无线电。您只需为radios 实现新的处理程序。由于他们将更改 input number,因此当函数触发条件将选择的收音机时,将已被选中。

如果您想防止事件冒泡并触发其他功能,您可以调用stopPropagation.

另一种选择是#quantity直接定位而不是.mycontainer,并且该函数不会触发,因为它是兄弟元素而不是祖先元素。

$('.mycontainer').on('click', function() {
  if (parseInt($('#quantity').val(), 10) >= '5') {
    $('#2radio').prop('checked', true);
  } else {
    $('#1radio').prop('checked', true);
  }
})

$('[type=radio]').click(function(e) {
  e.stopPropagation();
  $('#quantity').val($(this).val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="mycontainer">
  <input type="number" id="quantity" name="quantity" value="1"><br><br>
  <input type="radio" id="1radio" name="radio" value="1"><label for="1radio">radio button #1</label><br><br>
  <input type="radio" id="2radio" name="radio" value="5"><label for="2radio">radio button #2</label>
<div>


推荐阅读