是否有任何功能可以帮助转义jquery的选择器中包含的所有元字符? [英] is there any function which can help escape all meta-characters contained in jquery‘s selector?

查看:79
本文介绍了是否有任何功能可以帮助转义jquery的选择器中包含的所有元字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接从jQuery文档:

Straight from jquery docs:

如果您希望使用任何元字符(例如!"#$%&'()*+,./:;<=>?@[\]^&a{|}~)作为名称的文字部分),则必须使用两个反斜杠对字符进行转义:\.例​​如,如果您的元素具有,则可以使用选择器$("#foo\\.bar").

If you wish to use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\]^&a{|}~) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar").

我想知道有什么功能可以帮助我摆脱那些元字符吗?

I want to know is there any function can help me to escape those meta-charcters?

推荐答案

查看

Check out this video about jQuery bugs, the author has a function he wrote that uses regexs to properly escape all jQuery selectors @52:18. Side note: the video is great, every developer using jQuery should watch it.

为后代而转录:

String.prototype.escapeSelector = function () {
    return this.replace(
        /([$%&()*+,./:;<=>?@\[\\\]^\{|}~])/g,
        '\\$1'
    );
};

您将这样使用:

$('#' + 'foo.bar'.escapeSelector());

这篇关于是否有任何功能可以帮助转义jquery的选择器中包含的所有元字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆