如何在 jQuery 中切换属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6617475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to toggle attribute in jQuery
提问by TJ Desantes
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?
怎么做?
回答by lonesomeday
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 的返回值被设置为新的属性值。
$(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
元素closest
,这应该更可靠和有效。
回答by SEoF
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 指出的那样 - 标签可能最适合您的情况
回答by artlung
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,并<label>
在图像周围简单地放置标签,然后将它们与您的复选框相关联以获得相同的效果。只需将<span>
html 中的s替换为<label>
.
回答by brenjt
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');
});
回答by user1429980
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");
}
});
});