Jquery, get 'this'从条件中选择

Jquery, getting 'this' selector from a conditional

本文关键字:条件 选择 this Jquery get      更新时间:2023-09-26

我的页面上有几个元素与'checkbox'类。单击后,将选中相应的复选框输入。但是,我需要让JQuery在页面首次加载时检查复选框元素是否处于活动状态,并在那时相应地检查复选框输入。

由于在我的页面上有多个"复选框"类,我使用了"this"选择器之前,它工作得很好,但我不知道如何使它做到这一点与我的页面加载没有我之前使用的。click操作的条件。这是我想要做的:

if($('.checkbox').hasClass('active')) {
    $('[name="'+$(this).attr('rel')+'"]').prop('checked', true); 
}

显然'this'选择器不知道我指的是什么。有更好的方法吗?因为它要检查一堆元素而不是一个,所以我很困惑。谢谢!

你只能在jQuery函数的上下文中使用this,所以在这个范围内,它不会引用任何.checkbox

你可以用。each代替:

$('.checkbox.active').each(function() {
    // In this context, this refers to the DOM element represented by .checkbox.active
    $('[name="'+this.rel+'"]').prop('checked', true); 
});

each函数可能适合您的需要:

$('.checkbox').each(function() {
    var $this = $(this);
    if ($this.hasClass('active')) {
        $('[name="'+$this.attr('rel')+'"]').prop('checked', true); 
    }
});

如果active类不存在时必须勾选复选框,则:

$('.checkbox').each(function() {
    var $this = $(this);
    $('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active')); 
});