最近在开发一个界面时发现了某些特殊情况下ID选择器就会出现无效的情况,查明是ID选择器中的不能包含特殊字符的原因。本文将介绍解决方法。

问题的原因是动态生成的Dom 元素的ID中包含“=”导致(你可能会问为什么会在ID中有“=”号,我只能说这种状况尽管不多,但是有,比方我的状况,我的ID是某个字符串Base64编码之后的字符串)。

JQuery ID选择器中的不能包括特别字符的处理  特殊字符 ID选择器 第1张

JQuery中的1.2.6版别至1.3.2版别都有这种状况,下面是测验的代码:

view plaincopy to clipboardprint?
<!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>

<!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的源代码能够看到堆选择器的解析有这么一段:

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呈现。。随意,本文仅仅为了我们遇到类似问题时能够快速找到问题。

【修改引荐】

  1. 运用jQuery和PHP构建一个受Ajax驱动的Web页面
  2. 运用 jQuery 简化 Ajax 开发
  3. 跟ASP.NET MVC一同运用jQuery
转载请说明出处
知优网 » JQuery ID选择器中的不能包括特别字符的处理

发表评论

您需要后才能发表评论