简体   繁体   English

未选中JQuery toggleClass()复选框

[英]JQuery toggleClass() checkbox unchecked

Hi Please check below code - 嗨请检查以下代码 -

HTML HTML

<div class="manage-user-freind" style="line-height:18px; cursor:pointer;">
  <span style="color:blue;">
    <img src="'+pageUrl+'/img/user-16x16.png" height="14" style="float:left; padding-top:2px;" /><input class="chk" type="checkbox" value="10" />pieter
  </span>
</div>

<div class="manage-user-freind" style="line-height:18px; cursor:pointer;">
  <span style="color:blue;">
    <img src="'+pageUrl+'/img/user-16x16.png" height="14" style="float:left; padding-top:2px;" /><input class="chk" type="checkbox" value="12" />john
  </span>
</div>

JQuery JQuery的

$('.manage-user-freind').click(function(){
     $(this).toggleClass('clicked',function(){
            $('.chk').prop('checked', true);
     });
});

CSS CSS

.clicked {
  background-color: yellow;
}

I have used toggleClass() function. 我用过toggleClass()函数。 toggleClass is working fine but all the check-boxes clicked also not unchecked the current checkbox . toggleClass工作正常,但点击的所有复选框也没有取消选中当前复选框。

I need when I will click any div first show that div in yellow color along with current checkbox checked. 我需要当我点击任何div时首先显示div为黄色并选中当前复选框。 Again clicking on that yellow color div will remove and also checkbox will unchecked. 再次单击该黄色颜色div将删除,并且复选框将取消选中。

Thanks. 谢谢。

Sorry for my English wording. 抱歉我的英文措辞。 :( :(

Try this: 尝试这个:

$('.manage-user-freind').on('click', function() {
    $(this).toggleClass('clicked').find('.chk').prop('checked', $(this).hasClass('clicked'));
});

Demo: https://jsfiddle.net/tusharj/d84z5vub/1/ 演示: https//jsfiddle.net/tusharj/d84z5vub/1/

$.toggleClass don't have callback function. $.toggleClass没有回调函数。 It's not async function, so you can move $('.chk').prop('checked', true); 它不是异步函数,所以你可以移动$('.chk').prop('checked', true); to next statement along toggling class: 切换到下一个语句:

$(this).toggleClass('clicked');
$('.chk').prop('checked', true);

To check and uncheck, this code should work: 要检查和取消选中,此代码应该有效:

$('.manage-user-freind').click(function(){
     $(this).toggleClass('clicked');
     var checkbox = $(this).find('.chk');
     checkbox.prop('checked', !checkbox.prop("checked"));
});

Here is a Fiddle. 这是一个小提琴。

According to this: jquery function on toggleClass complete? 根据这个: toggleClass上的jquery函数完成了吗?

you can use premise to wait until class will be changed 您可以使用前提等待课程改变

$(this).toggleClass('clicked').promise().done(function(){
    alert('a');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM