JQuery ID選擇器中的不能包含特殊字符的處理
問(wèn)題的起因是動(dòng)態(tài)生成的Dom 元素的ID中包含“=”導(dǎo)致(你可能會(huì)問(wèn)為什么會(huì)在ID中有“=”號(hào),我只能說(shuō)這種情況雖然不多,但是有,比如我的情況,我的ID是某個(gè)字符串Base64編碼之后的字符串)。
JQuery中的1.2.6版本至1.3.2版本都有這種情況,下面是測(cè)試的代碼:
view plaincopy to clipboardprint?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<html xmlns="<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>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<html xmlns="<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的源代碼可以看到堆選擇器的解析有這么一段:
view plaincopy to clipboardprint?
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] );
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是個(gè)正則表達(dá)式對(duì)象
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
^#([\w-]+)$是判斷ID選擇符,很明顯只能匹配包括下劃線的任何英文字符數(shù)字和下劃線中劃線。
所以其他的字符如= @等都會(huì)出現(xiàn)問(wèn)題。你解決的辦法可以修改JQuery代碼中的正則表達(dá)式
如我要添加=號(hào),那么我可以改成quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-\=]+)$/,
或者避免出現(xiàn)=的ID出現(xiàn)。。隨便,本文只是為了大家遇到類似問(wèn)題時(shí)可以快速找到問(wèn)題。
【編輯推薦】