gpt4 book ai didi

javascript - 复选框默认图标不使用 jQuery 更新

转载 作者:太空宇宙 更新时间:2023-11-04 15:07:13 25 4
gpt4 key购买 nike

我在 <a> 上有一个简单的脚本单击它选中或取消选中复选框。第一次一切正常,但是一旦使用 jQuery 更改了值,它就不会更新(尽管在 Chrome 的检查器中,属性 checked="checked" 被添加/删除)。

HTML:

<a href="#" class="js-tick-untick-checkbox">
<input type="checkbox" class="send-invite-checkbox" />
Something something in the month of May
</a>

jQuery:

$('.js-tick-untick-checkbox').click(function() {
var checkbox = $(this).find('.send-invite-checkbox');

if ($(checkbox).attr('checked') === 'checked') {
checkbox.removeAttr('checked');
$(this).removeClass('selected-element');
} else {
checkbox.attr('checked', 'checked');
$(this).addClass('selected-element');
}
return false;
})

查看演示:http://jsfiddle.net/y3e0jfc6/

我尝试了各种其他选项,例如 checked="true"/checked="false" , 没有工作...

有什么想法吗?谢谢。

最佳答案

使用prop()而不是 attr()

来自 docs :

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.

$('.js-tick-untick-checkbox').click(function () {
var checkbox = $(this).find('.send-invite-checkbox');
if ($(checkbox).prop('checked')) {
checkbox.prop('checked', false);
$(this).removeClass('selected-element');
} else {
checkbox.prop('checked', true);
$(this).addClass('selected-element');
}
return false;
})

Demo

旁注:您可以像 this 那样做也是。

关于javascript - 复选框默认图标不使用 jQuery 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25283917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com