简体   繁体   English

如何通过使用jQuery检查父元素的类

[英]How to check class of parent element by using jquery

This is my second script in jquery. 这是我在jquery中的第二个脚本。 What I want to do: 我想做的事:

<span class="">
    <input name="personalData1" id="personalData1" value="0" checked="checked" type="checkbox">
</span>

This is default. 这是默认值。 When user click on this input field, the system add class checked to span. 当用户单击此输入字段时,系统将添加选中跨度的类。 So the results is: 因此结果是:

<span class="checked">
    <input name="personalData1" id="personalData1" value="0" checked="checked" type="checkbox">
</span>

I want to change value of this input. 我想更改此输入的值。 If it's checked than value is 1 in other way it will be 0. My code: 如果选中它,否则以其他方式将value设为1,则它将为0。我的代码:

$(document).ready(function () {
    $("#personalData1").change(function () {
        $('#opc_payment_methods-content').removeClass('hide');

        if ($('#personalData1 > span').hasClass('checked')) {
            window.alert('ok');
        }
    });
});

Something is wrong with this if statement, I can not get in and display alert. 此if语句出了点问题,我无法进入并显示警报。 Thanks for any help. 谢谢你的帮助。

Kind regards 亲切的问候

You should use parent method, for more information Jquery .parent() 您应该使用parent方法,以获取更多信息Jquery .parent()

So in your function it will be: 因此,在您的函数中它将是:

$(document).ready(function () {
    $("#personalData1").change(function () {
        $('#opc_payment_methods-content').removeClass('hide');

        if ($('#personalData1').parent().hasClass('checked') == false) {
            window.alert('ok');
            $('#personalData1').parent().addClass('checked');
        }
    });
});

Hope it helps, 希望能帮助到你,

Your referencing the checkbox $('#personalData1 > span') as the parent. 您将复选框$('#personalData1 > span')引用为父级。 instead do this: 而是这样做:

 if ($('#personalData1').parent().hasClass('checked')) {
     window.alert('ok');
  }

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

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