JQuery ID選擇器中的不能包含特殊字符的處理
問題的起因是動態生成的Dom 元素的ID中包含“=”導致(你可能會問為什么會在ID中有“=”號,我只能說這種情況雖然不多,但是有,比如我的情況,我的ID是某個字符串Base64編碼之后的字符串)。
JQuery中的1.2.6版本至1.3.2版本都有這種情況,下面是測試的代碼:
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是個正則表達式對象
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
^#([\w-]+)$是判斷ID選擇符,很明顯只能匹配包括下劃線的任何英文字符數字和下劃線中劃線。
所以其他的字符如= @等都會出現問題。你解決的辦法可以修改JQuery代碼中的正則表達式
如我要添加=號,那么我可以改成quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-\=]+)$/,
或者避免出現=的ID出現。。隨便,本文只是為了大家遇到類似問題時可以快速找到問題。
【編輯推薦】