[翻译]  How to toggle attribute in jQuery

[CHINESE]  如何在jQuery中切换属性


I'm trying to use images as checkboxes. The following would work fine if it were radios instead of checkboxes that I was targeting but with checkboxes the problem is I can't select an element by clicking on it again after selecting it.

我正在尝试使用图像作为复选框。以下可以正常工作,如果它是无线电而不是我目标的复选框,但复选框问题是我无法通过选择后再次单击它来选择元素。

// image checkbox
$('#imageCheckBoxes img').click(function() {
    $(this).parent('span').find('input:checkbox').attr('checked', 'checked');
});
<div id="imageCheckBoxes">
    <ul>
        <li><a href="">Africa</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">Asia/Pacific Islands</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">Australia</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">Central/South America</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">Europe/Russia</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">North America</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
        <li><a href="">United Kingdom</a>  <span><img src="images/checkbox-inactive.png" /><input type="checkbox" name="" value="" /></span>
        </li>
    </ul>
</div>

I need to basically toggle the check attr() part.

我需要基本上切换检查attr()部分。

How to do that?

怎么做?

5 个解决方案

#1


57  

I'd do this by passing a function to prop (since jQuery 1.6, attr before). The return value of this is set as the new property value.

我通过将函数传递给prop来实现这一点(因为之前是jQuery 1.6,attr)。将其返回值设置为新属性值。

$(this)
    .closest('li')
        .find('input:checkbox').prop('checked', function(idx, oldProp) {
            return !oldProp;
        });

The key fact here is that you can pass true or false to prop to set the checked property. oldProp is the existing value of the property (which will be either true or false), so !oldProp is the inversion: checked elements are unchecked and vice versa.

这里的关键事实是你可以将true或false传递给prop来设置checked属性。 oldProp是属性的现有值(将为true或false),因此!oldProp是反转:已选中已检查的元素,反之亦然。

Note that I have also changed your code to look for the closest ancestor li element with closest, which should be more reliable and effective.

请注意,我还更改了您的代码以查找最接近的祖先li元素,它应该更加可靠和有效。

#2


4  

You could add a rather basic jQuery extension, that works in the same way as "toggle()" and "toggle(showOrHide)" but for attributes - "toggleAttr(attribute)" and "toggleAttr(attribute, addOrRemove)"

您可以添加一个相当基本的jQuery扩展,其工作方式与“toggle()”和“toggle(showOrHide)”相同,但对于属性 - “toggleAttr(attribute)”和“toggleAttr(attribute,addOrRemove)”

$.fn.toggleAttr = function(a, b) {
    var c = (b === undefined);
    return this.each(function() {
        if((c && !$(this).is("["+a+"]")) || (!c && b)) $(this).attr(a,a);
        else $(this).removeAttr(a);
    });
};

Note, this is xhtml compatible, and is designed for attributes such as "disabled", "enabled", "checked", "selected" and so on.

注意,这是xhtml兼容的,并且设计用于诸如“禁用”,“启用”,“选中”,“选择”等属性。

Example of use (for your scenario):

使用示例(适用于您的场景):

$('#imageCheckBoxes img').click(function() {
    $(this).parent('span').find('input:checkbox').toggleAttr('checked');
}

EDIT - though as pointed out by artlung - a label is probably best for your scenario

编辑 - 尽管artlung指出 - 标签可能最适合您的场景

#3


2  

Another possible approach:

另一种可行方法:

$('#imageCheckBoxes').delegate('img', 'click', function(){
    var $associatedCheckbox = $(this).siblings('input:checkbox');
    if ($associatedCheckbox.is(':checked')){
        $(this).removeClass('checked');
        $associatedCheckbox.removeAttr('checked');
    } else {
        $(this).addClass('checked');
        $associatedCheckbox.attr('checked', 'checked');
    }
});

I'm using delegate(), though you could just as easily use your standard click() or a bind() call to add the listening function.

我正在使用delegate(),尽管你可以轻松地使用标准的click()或bind()调用来添加监听功能。

I also have added some code to add a class to the image. If you, say, wanted to give visual feedback to the user, you could implement that with your .checked class on those images.

我还添加了一些代码来为图像添加一个类。例如,如果您想向用户提供视觉反馈,则可以使用.checked类在这些图像上实现。

#imageCheckboxes img {
  border: 2px solid #fff;
}
/* feedback for your users! */
#imageCheckboxes img.checked {
  border: 2px solid #6f6;
}

Now, it strikes me that you could also avoid JavaScript for this, and simple put <label> tags around your images, and then associate them with your checkboxes to get the same effect. Just replace your <span>s in your html with <label>.

现在,让我感到震惊的是你也可以为此避免使用JavaScript,并简单地在图像周围放置

#4


1  

Try this.

尝试这个。

$('#imageCheckBoxes img').click(function() {
    var el = $(this).parent('span').find('input:checkbox');
    if(el.is(':checked'))
        el.attr('checked', '');
    else
        el.attr('checked', 'checked');
});

#5


0  

My solution was a little more clever:

我的解决方案更聪明一点:

var $formContainer = $(".form-container"),
    $myCheckbox = $formContainer.find(".my-checkbox"),
    $requiredFields = $formContainer.find("input[required], textarea[required], select[required]").removeAttr("required"); // remove the required attribute on all required form inputs
$myCheckbox.change(function () {
    $formContainer.toggle("fast", function() {
        if ($(this).is(":visible")) {
            $requiredFields.attr("required", true);
        }
        else {
            $requiredFields.removeAttr("required");
        }
    });
});

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号