javascript - 脚本的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>
解决方案
每当您检查 aradio
时,该事件就会冒泡并触发该.mycontainer
功能,并且由于该值未更改,因此它会重新选择另一个无线电。您只需为radio
s 实现新的处理程序。由于他们将更改 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>
推荐阅读
- swift - swiftUI 中的可识别协议... id 属性... var vs let
- c - 填充字节是否在内存分配器中被视为已分配或未分配?
- javascript - 这两个javascript代码之间的区别
- python - AIO Castle Cavalry - 我的代码太慢了,有什么办法可以缩短它吗?
- php - Simplephp 和数组
- c# - 统一调整玩家行为以适应 AI
- python - 继续调用函数,直到满足条件 Python
- javascript - 持续时间超过 24 小时的 Jquery 输入掩码
- cmake - 使用 CMake,如何在 gtest_discover_tests --gtest_list_tests 调用上设置环境属性?
- c# - 无法加载文件或程序集 'System.ComponentModel.Annotations,版本 = 4.2.0.0,