簡體   English   中英

使用javascript以使數字對齊並且其他對齊

[英]Using javascript so that the numerics are right aligned and others are left aligned

我用過這個javascript函數:

$(document).ready(function(){
    $("td").each(function() {
       if (parseInt($(this).text()) > 0) {
            $(this).css("text-align", "right");
        }
    });
});

通過這一切,所有數字都是正確對齊的。 但我希望輸入的字符串應該左對齊。 我認為通過使用NaN是可能的,但我不知道如何使用它。 有人可以告訴我使用NaN或其他功能的方法嗎?

你可以這樣做:

$(document).ready(function(){
    $("td").each(function() {
       var item = $(this);
       if (item.text().match(/^-?\d+$/)) {
            item.css("text-align", "right");
        } else {
            item.css("text-align", "left");
        }
    });
});

工作示例: http//jsfiddle.net/jfriend00/MyqrG/

為什么不能使用typeof運算符來確定數字和字符串。

$( document ).ready( function() {
    $( "td" ).each( function() {
       var textVal = $( this ).text();
       var type = !isNaN(parseFloat(textVal)) && isFinite(textVal);

       if ( !type ) {
            $( this ).css( "text-align", "left" );
       } else if ( type ) {
            $( this ).css( "text-align", "right" );
       }
    });
});

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM