js关于处理字符串中的空格问题方法总结

JavaScript029

js关于处理字符串中的空格问题方法总结,第1张

一、函数

 

function trim(str){ //删除左右两端的空格

return str.replace(/(^\s )|(\s $)/g, "")

}

function ltrim(str){ //删除左边的空格

return str.replace(/(^\s*)/g,"")

}

function rtrim(str){ //删除右边的空格

return str.replace(/(\s*$)/g,"")

}

函数调用 trim(str)

二、js对象的方法

String.prototype.trim=function(){

return this.replace(/(^\s )|(\s $)/g, "")

}

String.prototype.ltrim=function(){

return this.replace(/(^\s*)/g,"")

}

String.prototype.rtrim=function(){

return this.replace(/(\s*$)/g,"")

}

类中方法调用 str.trim()

三、将公共方法提取到一个或多个公共js文件,需要的时候直接引用;

触发keydown事件需要控件获取到焦点,div控件无法像input控件那样获取到焦点,无法触发keydown事件,因此可以将keydown事件绑定在document上,然后用div的hover事件去判断鼠标是否正在div上。

<!DOCTYPE html>

<!--STATUS OK-->

<html>

<head>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

    <meta http-equiv="content-type" content="text/htmlcharset=utf-8" />

    <meta property="wb:webmaster" content="3aababe5ed22e23c" />

    <meta name="referrer" content="always" />

    <title>s鼠标悬浮事件嵌套键盘事件问题,点击空格并没有响应,求大神来帮助!_百度知道</title>

    <style>

        .divTest { width: 200px height: 200px border: 1px solid #CCC }

    </style>

    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        var divFocus = false

        $(function () {

            $(".divTest").hover(function () {

                divFocus = true

                $(".divTest").text(2)

            }, function () {

                divFocus = false

                $(".divTest").text("")

            })

            $(document).keydown(function (event) {

                if (!divFocus) {

                    return

                }

                if (event.keyCode != 32) {

                    return

                }

                $(".divTest").text(101)

            })

        })

    </script>

</head>

<body>

    <div class="divTest"></div>

</body>

</html>

你好,如果你想通过js模拟按键控制键盘的话,建议不要这样做,因为只能通过调用Wscript或者ActiveX来实现,而要能正常使用这些,浏览器都需要取得用户的许可后才会允许使用的。

如果只是要实现某个特定的网页上的按空格键的效果的话,可以直接调用空格键绑定的事件函数即可.