我有一个复选框,我想每 2 秒使用 setInterval 选中/取消选中它。
但它只会被选中/取消选中一次。
此外,当我检查 DOM 时,我可以看到它的值并且 checked
属性正在更新,但它没有反射(reflect)在 View 中。
这是我的代码
HTML
<input type="checkbox" name="paid" id="paid-change" value = "1">
JS
var getCheckBox = $("#paid-change");
function check(){
getCheckBox.attr('checked',true);
getCheckBox.val("1")
}
function uncheck(){
getCheckBox.attr('checked',false);
getCheckBox.val("0")
}
// check/uncheck in every 2 seconds
setInterval(function(){
switch (getCheckBox.val()){ //get checkbox value
case "0":
check() // if value is 0 check it
break;
case "1":
uncheck() //uncheck it
break;
}
},2000)
这是一个jsfiddle .
检查元素,你的属性正在更新但没有反射(reflect)在 View 上。
知道我哪里出错了吗?
最佳答案
不要使用 attr()
来设置 checked
属性,而是使用 prop()
。
getCheckBox.prop('checked', true);
代码可以改写为
// Cache checkbox object
var checkbox = $("#paid-change");
// Function to toggle the checkbox value and state
function toggleCheckbox() {
// Change the 'checked' property
checkbox.prop('checked', function(i, checked) {
return !checked; // Invert the checked status
}).val(function(i, val) {
return +this.checked; // Change the value
});
}
setInterval(toggleCheckbox, 2000); // Call the function after each 2 seconds
关于javascript - 复选框未选中,但属性值正在更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762767/