zoukankan      html  css  js  c++  java
  • 限制字符串长度

    在开发web页面时,表单内字符串过长而超出规定长度会导致一些不必要的麻烦,
    比如:
         用户注册时系统限制的用户名只有8个英文字符,但是用户输入了10个或者更多的字符时,
    就可能造成昵称页面显示错行,或者昵称被截断的问题。
    下面是限制字符串长度的解决方案:
    1,通过使用JavaScript原生的获取属性的方法:
    #id.getAttribute("data-length");

    来判断输入框的限制长度。

    2,通过比对输入的长度与输入框的限制长度属性进行比较:

    if(输入长度 > 属性长度){
      value = value.substr(0,属性长度); //超过长度自动截取  
    }

    HTML代码:

    <input type="text" data-length="6" id="limitLength" name="Iname"/>

    JavaScript方法:

    var  maxLength = function(tThis){
        var _v = tThis.value.replace(maxRegex,''), //获取输入文本(去除空格)
        _vLen = _v.length,
        dataLength = tThis.getAttribute('data-length'), //获取限制长度
        dataModel = tThis.getAttribute('data-model'),
        subLen = dataLength;
                        
        if(_vLen > dataLength){
        tThis.value = _v.substr(0,subLen);  //判断长度,超过长度自动截取
        }
    }

    完整的javaScript代码:

    var limitLength = document.getElementById('limitLength');
                var maxRegex = /s+/g;//去除空格的正则表达式
                var  maxLength = function(tThis){
                    var _v = tThis.value.replace(maxRegex,''), //获取输入文本(去除空格)
                        _vLen = _v.length,
                        dataLength = tThis.getAttribute('data-length'), //获取限制长度
                        dataModel = tThis.getAttribute('data-model'),
                        subLen = dataLength;
                        
                    if(_vLen > dataLength){
                        tThis.value = _v.substr(0,subLen);  //判断长度,超过长度自动截取
                    }
                }
                
                limitLength.onblur = function(){
                    maxLength(this);
                }
                
                limitLength.onkeyup = function(){
                    maxLength(this);
                }
                
                limitLength.onfocus = function(){
                    maxLength(this);
                }
    View Code

    如果您感兴趣,请点一下推荐额,谢谢!

    扫码关注微信公众号:

  • 相关阅读:
    交换机工作原理
    MyBatis框架的使用及源码分析(一) 配置与使用
    MySQL5.6安装步骤
    mysql创建用户,并授权
    命令行访问远程mysql数据库
    [mybatis] mybatis错误:Invalid bound statement (not found)
    【大数据】每秒十万笔交易的数据架构解读
    【mybaits】Mybatis中模糊查询的各种写法
    【redis】 linux 下redis 集群环境搭建
    [linux] linux下编译安装zlib
  • 原文地址:https://www.cnblogs.com/White-Quality/p/5518666.html
Copyright © 2011-2022 走看看