简体   繁体   English

jQuery试图检查一个复选框

[英]JQuery trying to check a checkbox

I am trying to check a check box with jquery alone and then doing a return false as there is other jquery methods i dont want to affect the check box. 我试图单独检查一个带有jquery的复选框,然后执行return false,因为我不想影响其他的jquery方法。 But for some reason the check box is not checking or unchecking. 但是由于某种原因,该复选框没有选中或取消选中。 I need the return false in there as there is other functions which affect the outside element of the checkbox. 我需要在其中返回return false,因为还有其他功能会影响复选框的外部元素。

 $("#p h1 input").click(function (event) {

    if ($(this).is(':checked'))
    {
        $(this).prop('checked', false);
    }
    else
    {
        $(this).prop('checked', true);
    }

    return false;
});

ok additional i have this even on the h1 好的,我在H1上也有这个

$("#p h1").click(function (event) {
        $(this).next(".content").slideToggle();

        if ($(this).hasClass("on")) {
            $(this).find("span").addClass("fa-angle-up");
            $(this).find("span").removeClass("fa-angle-down");
        }
        else {
            $(this).find("span").removeClass("fa-angle-up");
            $(this).find("span").addClass("fa-angle-down");
        }

        $(this).toggleClass("on");
    });

The check box is inside the h1. 该复选框位于h1内部。

I don't want the slide function or anything from the second click event to occur when the checkbox is clicked. 我不希望在单击复选框时发生滑动功能或第二单击事件中的任何事件。

This is the html 这是HTML

<h1>Set<span class="fa fa-angle-up"></span>@Html.CheckBoxFor(model => model.Confirm)</h1>

I don't want the slide function or anything from the second click event to occur when the checkbox is clicked. 我不希望在单击复选框时发生滑动功能或第二单击事件中的任何事件。

In this case you can check what the target of the event was, and not perform your logic if it was the checkbox. 在这种情况下,您可以检查事件的target是什么,如果是复选框,则不执行逻辑。 To do this you can use jQuery's is() function. 为此,您可以使用jQuery的is()函数。

Also note that your if logic can be simplified by simply using toggleClass() instead. 还要注意,只需使用toggleClass()即可简化if逻辑。 Try this: 尝试这个:

 $("#p h1").click(function(e) { if ($(e.target).is(':checkbox')) return; var $h1 = $(this); $h1.next(".content").slideToggle(); $h1.toggleClass('on').find('span').toggleClass('fa-angle-up fa-angle-down'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <div id="p"> <h1 class="on"> Set <span class="fa fa-angle-up"></span> <input type="checkbox" name="Confirm" /> </h1> </div> 

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

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