prop() 方法
prop() 方法用于选中或者取消选中复选框,例如单击按钮。
该方法需要 jQuery 1.6+ 版本。
在设置禁用和选中时,prop() 方法比 .attr() 方法有优势。
该方法操作已检查的属性并根据我们是要选中还是取消选中它来将其设置为 true 或者 false。
要取消选中单选按钮,我们可以使用 jQuery 脚本或者 JavaScript。
jQuery
如果我们想使用 jQuery,那么动态取消选中单选按钮的正确选择(例如单击按钮)将使用 prop() 方法。
让我们看看它是如何工作的:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js">
</script>
</head>
<body>
<div>
<label>
<input type="radio" name="check button" id="radiobtn1"> Radio Button 1</label>
<label>
<input type="radio" name="check button" id="radiobtn2"> Radio Button 2</label>
</div>
<div>
<button type="button" class="checkRadioBtn1">Checked Radio Button 1</button>
<button type="button" class="checkRadioBtn2">Checked Radio Button 2</button>
</div>
<script>
$(document).ready(function() {
$(".checkRadioBtn1").click(function() {
$("#radiobtn1").prop("checked", true);
});
$(".checkRadioBtn2").click(function() {
$("#radiobtn2").prop("checked", true);
});
});
</script>
</body>
</html>
JavaScript
这是取消选中单选按钮的 JavaScript 解决方案:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
</head>
<body>
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />
<script>
let radios = document.getElementsByTagName('input');
for(i = 0; i < radios.length; i++) {
radios[i].onclick = function(e) {
if(e.ctrlKey) {
this.checked = false;
}
}
}
</script>
</body>
</html>
日期:2020-06-02 22:16:27 来源:oir作者:oir
