代码之家  ›  专栏  ›  技术社区  ›  Pete Irfan TahirKheli

有没有办法测试元素中内容的类型

  •  1
  • Pete Irfan TahirKheli  · 技术社区  · 7 年前

    我试图使用javascript/jquery测试元素中的内容类型,但每当我从元素中获取内容时,它总是作为字符串返回:

    $('.test').each(function() {
        console.log(
          this.innerHTML.trim(), 
          typeof this.innerHTML, 
          typeof $(this).text(), 
          $.type(this.innerHTML.trim()),
          Number.isInteger(Number(this.innerHTML.trim()))
        );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test">
    1234
    </div>
    <div class="test">
    22.54
    </div>
    <div class="test">
    2test
    </div>

    有没有办法不用 typeof 这样我就可以解析这些数字,这样我就可以正确地对它们进行排序,而不是将它们作为字符串排序

    3 回复  |  直到 7 年前
        1
  •  1
  •   Nikola Lukic    7 年前

    这是检查函数的类型:

    $('.test').each(function() {
      
        var checktype = isNaN( this.innerHTML )
        if (checktype == false) { alert("number"); return;}
        else {
        
        alert( typeof this.innerHTML )
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test">
    1234c
    </div>
    <div class="test">
    22.54
    </div>
        2
  •  1
  •   Anwarus    7 年前

    例如,您可以使用函数 isNaN 检查文本(也接受字符串)是否不是数字。如果是数字 parseFloat + 签名以将变量解析为所需类型。

    $('.test').each(function() {
        var text = $(this).text();
        if(!isNaN(text))
        	text = +text;
        console.log(text + " " + typeof text);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test">
    1234
    </div>
    <div class="test">
    22.54
    </div>
    <div class="test">
    normalText
    </div>
        3
  •  -1
  •   4b0 Agit    7 年前

    使用 parseInt 检查前 isInteger .

    $('.test').each(function() {
         console.log(Number.isInteger(parseInt(this.innerHTML.trim())))
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="test">
    1234
    </div>
    <div class="test">
    22.54
    </div>