开发者

JQUERY .each --- detecting if EACH finds 0

开发者 https://www.devze.com 2022-12-22 09:22 出处:网络
I have the following: $(\"span.findme\").each(function() { $(\"<li>\").text($(this).text()).appendTo(\"ul\");

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号