使用 jQuery 单击切换 [英] Click toggle with jQuery
问题描述
我使用了悬停功能,您可以在鼠标悬停时执行 x 以及在鼠标悬停时执行 y 和 mouseout.我正在尝试相同的点击,但它似乎不起作用:
I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
我希望在单击 div
时选中复选框,如果再次单击则取消选中 - 单击切换.
I want the checkbox to be checked when clicking on a div
, and unchecked if clicked again - a click toggle.
推荐答案
这很容易通过在每次单击时翻转复选框的当前选中"状态来完成.例子:
This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
或:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.is(':checked'));
});
或者,通过直接操作 DOM 'checked' 属性(即不使用 attr()
来获取被点击复选框的当前状态):
or, by directly manipulating the DOM 'checked' property (i.e. not using attr()
to fetch the current state of the clicked checkbox):
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox[0].checked);
});
...等等.
注意:从 jQuery 1.6 开始,复选框应该使用 prop
而不是 attr
:
Note: since jQuery 1.6, checkboxes should be set using prop
not attr
:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
});
这篇关于使用 jQuery 单击切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!