JQuery ID选择器中的不能包含特殊字符(=,@ etc.)

来源:互联网 发布:华东师大网络教育 编辑:程序博客网 时间:2024/06/03 21:47

本文来自编程入门网:http://www.bianceng.cn/webkf/jquery/201101/23736.htm


最近在开发一个界面时发现了某些特殊情况下ID选择器就会出现无效的情况,经查原来是的动态生成的Dom 元素的ID中包含“=”导致(你可能会问为什么会在ID中有“=”号,我只能说这种情况虽然不多,但是有,比如我的情况,我的ID是某个字符串Base64编码之后的字符串)。


JQuery中的1.2.6版本至1.3.2版本都有这种情况,下面是测试的代码:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head>    <title></title>    <script src="Javascript/jquery.1.3.2.js" type="text/javascript"></script>    <script type="text/javascript">        $(function() {                        var div = $("#hellodiv=");            if (div.length > 0) {                alert("获取到了Div");            }            else {                alert("哎呀ID中不能包含=");            }            var div2 = document.getElementById("hellodiv=");            if (div2) {                alert("我可以获取到哦");            }            else {                alert("哎呀我也获取不到");            }        });    </script></head><body>    <div id="hellodiv="></div></body></html>


查看Jquery的源代码可以看到堆选择器的解析有这么一段:


var match = quickExpr.exec( selector );            // Verify a match, and that no context was specified for #id            if ( match && (match[1] || !context) ) {                // HANDLE: $(html) -> $(array)                if ( match[1] )                    selector = jQuery.clean( [ match[1] ], context );                // HANDLE: $("#id")                else {                    var elem = document.getElementById( match[3] );



其中quickExpr是个正则表达式对象


quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,


^#([\w-]+)$是判断ID选择符,很明显只能匹配包括下划线的任何英文字符数字和下划线中划线。


所以其他的字符如= @等都会出现问题。你解决的办法可以修改JQuery代码中的正则表达式


如我要添加=号,那么我可以改成quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-\=]+)$/,


或者避免出现=的ID出现。。随便,本文只是为了大家遇到类似问题时可以快速找到问题。。



下面是我自己做的:

将jquery.js源码中的判断ID选择符
quickExpr =/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
改成
quickExpr =/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-\.]+)$/,
将支持id中包含点号。如<div id="dwg.dwgno"></div>
通过$("#dwg.dwgno")能进行识别。





原创粉丝点击