checking for number of selectors with jquery
I am trying to see if there are any tags which have the class="red" in the code. I thought that this w开发者_运维问答ould work but it isn't. How would I do this?
if ($("[class='red']").length <=0) /*if some of the entries are invalid (aka- have a red star)*/
{
alert('Some Entries are Invalid');
return false;
}
just need
if ($(".red").length) {
// have a least one tag with class red
}
This works because 0 is a falsey value; in the if expression if no tags with class red are found then length will be 0 and hence the if block will not be entered. If length has a value greater than 0 however (a truthy value), the if block will be entered.
Your original code doesn't work because the logic is the wrong way round (you'll be showing the alert if there are no tags with the class red) :)
精彩评论