如何逃避这个选择器使它工作?

时间:2014-05-30 04:13:14

标签: javascript jquery html jquery-selectors escaping

我有一台收音机

<input type="radio" name="<_WallForm>" value="=(1,2,3)">

使用脚本

n = n.replace('<', '\\<').replace('>', '\\>').replace('=', '\\=');
v = v.replace('<', '\\<').replace('>', '\\>').replace('=', '\\=');

f.find('input[type=radio][name=' + n + '][value=' + v +']').parent().parent().find('.selectPic').click();

错误

Uncaught Error: Syntax error, unrecognized expression: input[type=radio][name=\<_WallForm\>][value=\=(1,2,3)]

那怎么办? 谢谢。

2 个答案:

答案 0 :(得分:6)

你不需要逃避任何事情。只需在属性选择器中添加引号(并删除前几行):

f.find('input[type="radio"][name="' + n + '"][value="' + v +'"]').parent().parent().find('.selectPic').click();

这应该会产生一个像

这样的选择器
input[type="radio"][name="<_WallForm>"][value="=(1,2,3)"]

...您将注意到与您在HTML中引用属性值的方式类似。


在旁注中,需要对尖括号进行编码,以便HTML验证:

<input type="radio" name="&lt;_WallForm&gt;" value="=(1,2,3)">

但是你不必在你的选择器中反映这一点 - 事实上,如果你试图这样做,选择器可能会停止匹配,因为选择器中无法识别HTML实体引用;他们只是字面意思。

正如评论中所提到的,如果您避免使用尖括号等特殊字符,并尽可能使用任意值的&符号,您的生活会更轻松。

答案 1 :(得分:0)

你的单引号互相碰撞。尝试将您的陈述更改为此...

f.find('input[type="radio"][name="' + n + '"][value="' + v + '"]').parent().parent().find('.selectPic').click();