这是我所拥有的:
item.find('div:contains(' + name + ')')
但是,在某些情况下,名称包含括号。在一种情况下,名称具有以下值:
"brown (ok xl (1))"
并且 item.find('div:contains(' + name + ')') 不起作用。括号是问题所在。如何逃脱他们?
这是我所拥有的:
item.find('div:contains(' + name + ')')
但是,在某些情况下,名称包含括号。在一种情况下,名称具有以下值:
"brown (ok xl (1))"
并且 item.find('div:contains(' + name + ')') 不起作用。括号是问题所在。如何逃脱他们?
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")
.
Here is a function to escape special characters and return a valid jQuery selector. Pass your string to this function before use:
function jqSelector(str)
{
return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}
几天前我遇到了同样的问题,但由于某些奇怪的原因@Zeta 的解决方案对我不起作用,所以我想出了
name = name.replace(/(\(|\)).*/g,"");
item.find("div:contains(" + name +")");
它并不完美,但它有效:)
编辑
更好的正则表达式:
name = "(d)test thingie(assaf)(asdads".replace(/\(([^\)])*\)/g,"$1 ").replace(/\(|\)(.)*/g,"$1 ");
如果您想消除括号之间的所有内容,以便包含您可以使用的工作:
name = "(d)test thingie(assaf)(asdads".replace(/\(([^\)])*\)/g,"").replace(/\(|\)(.)*/g,"");
与属性值选择器一样,:contains() 括号内的文本可以写成裸词或用引号括起来。(来源)
所以简单地使用
item.find('div:contains(\'' + name + '\')')
/* or */
item.find('div:contains("' + name + '")')
name
请注意,如果有任何引号,则需要转义其中的其他引号。