用js怎么实现限制字符的长度最多为24个字符(包括中文、字母、数字、标点符号)。

JavaScript022

用js怎么实现限制字符的长度最多为24个字符(包括中文、字母、数字、标点符号)。,第1张

//获取字符数,1个中文=2个英文字符

//参数:对象

function gw_js_checkform_str_len(str){

var value=str

var length=value.length

if(length>0){

for(var i=0i<lengthi++){

var value_substr=value.substr(i,1)//截取字符串

var value_escape=escape(value_substr)//编码

if(value_escape.indexOf('%u')>-1){length++} //是否搜索到指定字符串

//if(value_escape.length>3){length++} //也可使用此语句替换上一条语句

}

}

return length

}

<html>

    <head>

        <title>table_td</title>

        <style>

            td{

                border:1px solid black

                border-collapse:collapse

                width:60px

                height:20px                

            }

            table{

                border:1px solid black

                border-collapse:collapse

            }

        </style>

        <script>

            var limitLength = 2//限制多少个字数

            function limitLen(){

                var count = document.getElementsByTagName("td").length

                for(var i = 0i<counti++){

                    var s = document.getElementsByTagName("td")[i].innerHTML

                    document.getElementsByTagName("td")[i].title = s

                    if(s.length>limitLength){

                        document.getElementsByTagName("td")[i].innerHTML = s.substring(0,limitLength)+"..."

                    }

                    else if(s.length < limitLength){

                        for(var c = s.lengthc<limitLength+3c++){//+3是因为后面三个...

                            s += " "    

                        }

                        document.getElementsByTagName("td")[i].innerHTML = s

                    }

                }

            }

             

        </script>

    </head>

    <body onLoad="limitLen()">

        <table>

            <tr>

                <td>123dddddddddddd</td>

                <td>345</td>

                <td>测试测试测试测试测试1</td>

                <td>345</td>

            </tr>

            <tr>

                <td></td>

                <td>空的</td>

                <td>测试测试测试测试测试测试测试测试2</td>

                <td>test</td>

            </tr>

        </table>

    </body>    

</html>