Jquery选择器特殊字符问题

场景: $("#" + AAA + ""),AAA代表某表单ID

当AAA为普通字符串时,ok;

当AAA含有特殊符号时(eg:a.b),获取不到该对象;

原因:特殊符号会进行转义,上面那种方式就无法获取的该ID。

// Does not work:
$( "#some:id" )
// Works!
$( "#some\\:id" )
// Does not work:
$( "#some.id" )
// Works!
$( "#some\\.id" )

解决:
The following function takes care of escaping these characters and places a "#" at the beginning of the ID string:
function jq( myid ) {
return "#" + myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
}
The function can be used like so:
$( jq( "some.id" ) )
 
 
http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/
posted @ 2016-05-04 18:43  上善若黄  阅读(462)  评论(0编辑  收藏  举报