JQUERY .each --- detecting if EACH finds 0
I have the following:
$("span.findme").each(function() {
$("<li>").text($(this).text()).appendTo("ul");
});
How can I, using the above, detect if EACH finds 0, if it's 0 I want to trigger 开发者_如何学编程an alert.
Thanks
Save the jQuery object to a variable and interrogate the length
property.
var spans = $("span.findme");
if (spans.length == 0) {
alert("none found!");
} else {
spans.each(function() {
$("<li>").text($(this).text()).appendTo("ul");
});
}
You can use Number to convert the text to a number and then do a numeric comparision to 0. For example:
$(function () {
$("span.findme").each(function () {
var nValue = Number($(this).text());
if (nValue == 0) {
alert('0 found');
}
$("<li>").text($(this).text()).appendTo("ul");
});
});
So if the text evalues to 0 then it is skipped. Here is an example:
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$(function () {
$("span.findme").each(function () {
var nValue = Number($(this).text());
if (nValue == 0) {
alert('0 found');
}
$("<li>").text($(this).text()).appendTo("ul");
});
});
</script>
</head>
<body>
<span class="findme">1</span><br />
<span class="findme">12</span><br />
<span class="findme">0</span><br />
<span class="findme">Test</span><br />
<span class="findme">0</span><br />
<span class="findme">0</span><br />
<span class="findme">1a</span><br />
<span class="findme">11</span><br />
<hr />
<ul>
</ul>
</body>
</html>
精彩评论