单击使用jQuery的切换 [英] Click toggle with jQuery
问题描述
我使用了悬停功能,在鼠标悬停时执行x,在鼠标悬停时执行y和y.我正在尝试相同的点击,但似乎不起作用:
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屋!