我有以下内容:
$(document).ready(function()
{
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").attr('checked', true);
});
});
当点击以在已选中和未选中之间切换时,我想要id="select-all-teammembers"
。 想法? 这不是几十行代码?
#1楼
//this toggles the checkbox, and fires its event if it has
$('input[type=checkbox]').trigger('click');
//or
$('input[type=checkbox]').click();
#2楼
假设它是一个必须切换复选框的图像,这对我有用
<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">
#3楼
我知道这是旧的,但问题有点模糊,因为切换可能意味着每个复选框都应切换其状态,无论是什么。 如果您有3个已选中且2未选中,则切换将使前3个未选中,最后2个选中。
为此,这里的解决方案都不起作用,因为它们使所有复选框具有相同的状态,而不是切换每个复选框的状态。 在许多复选框上执行$(':checkbox').prop('checked')
返回所有.checked
二进制属性之间的逻辑AND,即如果未选中其中一个,则返回的值为false
。
如果你想实际切换每个复选框状态而不是使它们全部相等,你需要使用.each()
,例如
$(':checkbox').each(function () { this.checked = !this.checked; });
请注意,您在处理程序中不需要$(this)
,因为.checked
属性存在于所有浏览器中。
#4楼
最基本的例子是:
// get DOM elements var checkbox = document.querySelector('input'), button = document.querySelector('button'); // bind "cilck" event on the button button.addEventListener('click', toggleCheckbox); // when clicking the button, toggle the checkbox function toggleCheckbox(){ checkbox.checked = !checkbox.checked; };
<input type="checkbox"> <button>Toggle checkbox</button>
#5楼
我认为触发点击更简单:
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").trigger('click');
});
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3165569