简体   繁体   English

jQuery检查元素不为空更改类

[英]jquery check element is not empty change class

When p.err is not empty I want to add the class p.err-wrapper. 当p.err不为空时,我要添加类p.err-wrapper。

<p class="err err-wrapper">not empty</p>
<p class="err"></p>


p.err {color:#ff0000, font-weight: bold; }
p.err-wrapper {background:#ffffdd; border:1px solid #ff0000; }

The app I am using adds an error msg over a form like this <p class="err"><?php get(error_msg) ?></p> 我正在使用的应用程序在这样的表单上添加了错误消息,例如<p class="err"><?php get(error_msg) ?></p>

It is added to the page whether there is an error or not. 无论是否存在错误,都会将其添加到页面。 As soon as there is an error <p class="err">Your first name is missing</p> , p.err decorates the contents of the <p> tag. 一旦出现错误<p class="err">Your first name is missing</p> ,p.err就会修饰<p>标记的内容。

I want to wrap the error in a border and a background. 我想将错误包装在边框和背景中。 The problems is because <p class="err"></p> is not conditionally added, I get a bordered background when there it no error. 问题是因为没有有条件添加<p class="err"></p> ,当没有错误时,我会得到带有边框的背景。

I want to add jquery that checks if <p class="err"></p> is not empty and then add the class p.err-wrapper, ie <p class="err err-wrapper"></p> . 我想添加jquery来检查<p class="err"></p>是否不为空,然后添加类p.err-wrapper,即<p class="err err-wrapper"></p>

I got it kind of working but i am so new at jquery. 我有点工作,但在jquery上我还很新。

You can use :not and :empty selectors. 您可以使用:not:empty选择器。

$('p.err:not(:empty)').addClass('err-wrapper');

http://jsfiddle.net/QYaJC/ http://jsfiddle.net/QYaJC/

Try using: 尝试使用:

$("p.err")
.filter(function(){return $(this).text().replace(/\s/g,"").length!=0})
.addClass("err-wrapper")​​​​​​​​;​​​​​​

The function passed as filter will trim any empty white spaces in the content. 作为过滤器传递的函数将修剪内容中的所有空白区域。

You can se a working demo here: http://jsfiddle.net/FNgDF/ 您可以在此处找到有效的演示: http : //jsfiddle.net/FNgDF/

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

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