这是一些 html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
这是一些 JavaScript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
我的目标是只要文本框中有值就选中该复选框,并在该值被删除时取消选中。这在 html 中似乎工作正常(我可以看到 checked="checked"
被添加到复选框中),但该复选框仅在第一次在文本框中输入内容时才显示为选中状态。
即使将 checked="checked"
添加到 html 中,为什么复选框仍显示为未选中状态?
最佳答案
使用元素属性而不是属性通过 JavaScript 更改其状态
checkbox.prop('checked',(textbox.val()!="") );
来自 .attr() 上的 jQuery 文档和 .prop() :
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
重点是 jQuery 自己的。只有选中的属性才会反射(reflect)和控制复选框的当前状态。选中的属性不应用于控制复选框状态。
关于javascript - jQuery 的复选框异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158302/