JQuery选择器

JQuery选择器规则, 借用了css1-3的规则(css选择器规则), 因为css本身也需要一套规则来索引DOM元素, 进而进行样式渲染,例如div.blue 表示目标DOM为 class属性值为blue的div元素。

同时JQuery添加了一些自己的规则, 例如按照查询连接元素 $("[href]")。

这样就衍生出, 一套元字符, 用于表达选择器 合法格式, 故对于 其他部分例如属性值在选择器中的情况, 例如查询href为 www.baidu.com的 链接, 则为 $("[href=‘www.baidu.com’]") 其中.就需要转义, 否则跟div.blue中作为格式的点冲突, 应该写为 $("[href=‘www\\.baidu\\.com’]")。

需要转义的字符, 包括 !"#$%&'()*+,./:;<=>?@[\]^`{|}~

详情见官网描述:

http://api.jquery.com/category/selectors/

Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document.

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

CSS 转义

根据上文描述给出的 W3C CSS规范,包括了 关于合法css选择器规则的全部集合。

http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

其中说明, ID中字符转义效果, 转义的反斜杠总被认为是 ID的一部分:

Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).

The identifier "te\st" is exactly the same identifier as "test".

css转义owasp建议:

https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values

Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the \HH escaping format. DO NOT use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. These escaping shortcuts are also susceptible to "escape-the-escape" attacks where the attacker sends \" and the vulnerable code turns that into \\" which enables the quote.

HTML5中的 选择器函数

HTML4没有选择器函数, JQuery提供封装接口, 提供选择器规则, 包含了css定位规则,

技术在革新,HTML5最终提供了js原生接口:

见:

HTML5中类jQuery选择器querySelector的使用  http://m.oschina.net/blog/282816

JQuery选择器敏感字符转义函数

jQuery的id选择器不支持特殊字符,需要转义(引入jqSelector()函数)

http://maijunjin.github.io/jquery/2013/10/11/jqueyr-id%E9%80%89%E6%8B%A9%E5%99%A8%E4%B8%8D%E6%94%AF%E6%8C%81%E7%89%B9%E6%AE%8A%E5%AD%97%E7%AC%A6%EF%BC%8C%E9%9C%80%E8%A6%81%E8%BD%AC%E4%B9%89.html

// Escapes special characters and returns a valid jQuery selector
function jqSelector(str)
{
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}

The HTML

<div id="id.with,special#characters" class="testElem[1]"></div>

The javascript

// ID selector
$('#'+jqSelector('id.with,special#characters')).text('My Selected Element'); // Class selector
$('.'+jqSelector('testElem[1]')).text('My Selected Element');

测试代码

<html>
<head>
<script type="text/javascript" src="./jquery-1.11.1.js" />
</head>
<body>
<script>alert("aaa");</script>
<input id="test" type="text" value="vt+\范" />
<script>
function stringToHex(str)
{
var val=""; for(var i = 0; i < str.length; i++)
{
val = val+ "\\"+"\\"+"\\x" + str.charCodeAt(i).toString(16);
  } return val;
} var afs = "'\"][vt+";
console.log("afs="+afs);
var b = stringToHex(afs);
console.log("stringToHex afs="+b);
b = eval("\""+b+"\"");
console.log("eval stringToHex afs="+b);
//b = eval("\""+b+"\"");
//console.log("eval eval stringToHex afs="+b); //alert($("input[value='"+b+"']").length); //length==1 FOUND
//alert($("input[value='\\v\\t\\+范']").length); //length==1 FOUND
//alert($("input[value='vt+\\\\范']").length); //length==1 FOUND
alert($("\in\put\[value='\\v\\t\+\\\\范']").length); //length==1 FOUND function stringToHex2(str)
{
var val=""; for(var i = 0; i < str.length; i++)
{
var charCode = str.charCodeAt(i);
var chari = str.charAt(i);
if ( charCode <= 127 )
val = val+ "\\"+ eval("\"" + "\\x" + str.charCodeAt(i).toString(16) + "\"");
else
val = val + chari;
  } return val;
} var afs = "vt+\\范";
console.log("afs="+afs);
var b = stringToHex2(afs);
console.log("stringToHex2 afs="+b);
//alert($("input[value='"+b+"']").length); //length==1 FOUND
//alert($("#te\s\\t").length); //length==1 FOUND The identifier "te\st" is exactly the same identifier as "test". function addSlash(srcStr)
{
var str = "";
var ch = "";
/*入参str为非string类型直接返回*/
if (typeof(srcStr) != "string")
{
return srcStr;
}
for(var i = 0; i < srcStr.length; i++)
{
ch = srcStr.substr(i, 1);
if( "\\" == ch )
{
ch = "\\\\";
}
else if( "\'" == ch )
{
ch = "\\\'";
}
else if( "\"" == ch )
{
ch = "\\\"";
} str = str + ch;
} return str;
}
//alert($("input[value='"+addSlash("vt+\\范")+"']").length); //length==1 FOUND //alert("input[value='\\\x27']");
//alert("input[value='"+b+"']");
</script>
</body>
</html>

JQuery选择器转义说明的更多相关文章

  1. 《锋利的jQuery(第2版)》笔记-第2章-jQuery选择器

    选择器是jQuery的根基,在jQuery中,对事件处理.遍历DOM和Ajax操作都依赖于选择器.熟练使用选择器,不仅可以简化代码,而且可以达到事半功倍的效果. 2.1 jQuery选择器是什么 1. ...

  2. jQuery选择器和DOM操作——《锋利的jQuery》(第2版)读书笔记1

    第1章 认识jQuery jQuery有以下优势: 轻量级: 强大的选择器: 出色的DOM操作的封装: 可靠的事件处理机制: 完善的Ajax: 不污染顶级变量: 出色的浏览器兼容性: 链式操作方式: ...

  3. 第二章 jQuery选择器

    选择器是行为与文档内容之间的纽带,其目的是能轻松的找到文档中的元素. jQuery中的选择器继承了CSS的风格.利用jQuery选择器,可以非常便捷快速地找出特定的DOM元素,然后给它们添加相应的行为 ...

  4. jQuery选择器 之详述

    jQuery选择器 一. 单词小计 Pervious 上一页sibling  同级first  第一last  最后not  不 Even  偶数    odd  奇数 header  页眉 一.jQ ...

  5. WEB入门之十三 jQuery选择器

    学习内容 jQuery层次选择器 jQuery属性选择器 jQuery表单选择器 jQuery过滤选择器 能力目标 熟悉jQuery各种选择器的使用场合 能熟练使用jQuery各种选择器 本章简介 上 ...

  6. Jquery 选择器 详解 js 判断字符串是否包含另外一个字符串

    Jquery 选择器 详解   在线文档地址:http://tool.oschina.net/apidocs/apidoc?api=jquery 各种在线工具地址:http://www.ostools ...

  7. jQuery(二):jQuery选择器

    jQuery选择器类似于CSS选择器,用来选取网页中的元素.例如: $("h3").css("background-color","red" ...

  8. 处理jQuery选择器中的特殊符号,如(、#等

    前几天解决一个外网问题,客服反馈页面数据加载不出来,首先看一下服务端日志也没报错异常,自己测试了一下,在chrome的Console发现有js报错,原来是js报错导致的数据加载不出来. 调试了一番,发 ...

  9. JQuery - 特殊字符转义(Uncaught Error: Syntax error, unrecognized expression:的处理)

    今天在改一个jQuery老项目时候,发现标签上的data-id中含有特殊字符时候报错Uncaught Error: Syntax error, unrecognized expression,如何处理 ...

随机推荐

  1. Android Fragment 生命周期及其API使用(建议使用自定义View替换Fragment)

    我为什么不主张使用Fragment Fragment:( Fragment就相当于一个有生命周期的View,它的生命周期被所在的Activity的生命周期管理 ) 生命周期回调说明: onAttach ...

  2. 当编译AFNetworking 2.0时出现了Undefined symbols for architecture i386

    当将AFNetworking添加到工程后编译时出现 Undefined symbols for architecture i386: "_SecCertificateCopyData&quo ...

  3. 洛谷 P1198 [JSOI2008]最大数 Label:线段树

    题目描述 现在请求你维护一个数列,要求提供以下两种操作: 1. 查询操作. 语法:Q L 功能:查询当前数列中末尾L个数中的最大的数,并输出这个数的值. 限制:L不超过当前数列的长度. 2. 插入操作 ...

  4. [Leetcode] Word BreakII

    Question: Given a string s and a dictionary of words dict, add spaces in s to construct a sentence w ...

  5. 20161005 NOIP 模拟赛 T2 解题报告

    beautiful 2.1 题目描述 一个长度为 n 的序列,对于每个位置 i 的数 ai 都有一个优美值,其定义是:找到序列中最 长的一段 [l, r],满足 l ≤ i ≤ r,且 [l, r] ...

  6. Invalid escape sequence(valid ones are \b \t \n \f \r \" \' \\)

    Invalid escape sequence(valid ones are \b \t \n \f \r \" \' \\) 在运行eclipse的相关程序代码时遇到了报错信息,查看控制台 ...

  7. 十、ios 模态窗口[实例]

    一.模态窗口概念 对话框一般分为两种类型:模态类型( modal )与非模态类型( modeless ).所谓模态对话框,就是指除非采取有效的关闭手段,用户的鼠标焦点或者输入光标将一直停留在其上的对话 ...

  8. 关于Go,你可能不注意的7件事(转的)

    http://tonybai.com/2015/09/17/7-things-you-may-not-pay-attation-to-in-go/ code https://github.com/bi ...

  9. 既然nodejs是单线程的,那么它怎么处理多请求高并发的?

    单线程解决高并发的思路就是采用非阻塞,异步编程的思想.简单概括就是当遇到非常耗时的IO操作时,采用非阻塞的方式,继续执行后面的代码,并且进入事件循环,当IO操作完成时,程序会被通知IO操作已经完成.主 ...

  10. Redis在windows下的安装使用

    下载的windows版本是redis-2.0.2,解压到D盘下: D:\redis-2.0.2 启动Redis服务(conf文件指定配置文件,若不指定则默认): D:\redis-2.0.2>r ...