仅当缺少类时 JQuery 输入复选框才设置类
仅当复选框缺少预先存在的类时,我才想将类设置为复选框。另请注意,它可能包含空类,然后也用新类覆盖它。 我正在使用以下内容,但我应该如何将条件添加到查找中?
$(this).find("input[type='radio'],input[type='checkbox']").addClass('IE8Border');
我正在朝这个方向努力:
$(this).find("input[type='radio'],input[type='checkbox']").each(function() {
$(this)[("[class='']")].addClass('IE8Border');
$(this)[(":not([class])")].addClass('IE8Border');
});
I want to set class to Checkbox only if preexising class is missing for the checkbox. Also note it it may contain empty class then also overwrite it with new class.
I'm using following but how should I add the condition to the find?
$(this).find("input[type='radio'],input[type='checkbox']").addClass('IE8Border');
I'm trying in this direction:
$(this).find("input[type='radio'],input[type='checkbox']").each(function() {
$(this)[("[class='']")].addClass('IE8Border');
$(this)[(":not([class])")].addClass('IE8Border');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我完全同意 Cybernate 的回答。但是您只是想添加一个类还是想覆盖?对于后一种尝试:
为了扩展 Cybernate 的答案,您还可以使用
not()
函数来代替filter()
。I fully agree on Cybernate's answer. But do you just want to add a class or do you want to overwrite? For the latter one try:
and to extend of Cybernate's answer, instead of
filter()
, you can also use thenot()
function.我有点不清楚你在问什么,所以我有两个答案给你:
如果你试图避免添加重复的类(即添加
IE8Border
两次),你不需要过滤任何东西。.addClass()
仅当元素上尚不存在该类时才会添加该类。如果您只想向那些还没有类的元素添加类,请尝试以下操作:
看看在这个演示中看看它的工作原理 ->
I'm a little unclear on what you're asking, so I have two answers for you:
If you are trying to avoid adding duplicate classes (i.e. adding
IE8Border
twice), you don't need to filter anything..addClass()
will only add the class if it doesn't already exist on the element.If you want to add a class to only those elements that don't already have a class, try this:
Have a look at this demo to see this working ->
您可以使用 hasClass 来检查是否已添加类。
试试这个:
您还可以避免使用以下版本的过滤器:
编辑:
如果您只是检查某个类是否存在,请尝试以下操作:
You can use hasClass to check if a class was already added.
Try this:
You can also avoid using filter with the following version:
EDIT:
If your check is just for existence of a class then try this: