jQuery - isSelector 函数
我没有找到任何对我的特定情况有帮助的东西,所以这里有一个问题:对于一个特定的字符串如何检查它是否是一个正确的 jQuery 选择器(暂时让我们变得简单并限制我们自己使用非自定义 jQuery 选择器) ,或者如果这太难了,有效的 CSS 选择器 - 基本上:
$.isSelector("div") = return true
$.isSelector("* [") = return false - unclosed attribute selector
$.isSelector("* []") = return false - empty attribute selector
$.isSelector("* [name]") = return true
$.isSelector("/hiThere") = return false - invalid / character
$.isSelector("body > ") = return false - > without following child selector
$.isSelector("body > [name=\\\[girls_just_want_to_have_fun\\\]].on a .beach") = return true
可能有一个内部 jQuery 函数可以进行检查(或 RegExp),但我的 voodoo 太差了,找不到它。
可能是这样的:
function isSelector(string)
{
try
{
$(string);
return true;
}
catch(e)
{
return false;
}
}
可以解决问题,但似乎有点极端。
干杯!
I've failed to find anything which would be helpful in my particular situation, so here's a question: for a specific string how to check if it's a proper jQuery selector (for time being let's make it simple and restrain ourselves to noncustom jQuery selectors), or if that's too hard, valid CSS selector - basically:
$.isSelector("div") = return true
$.isSelector("* [") = return false - unclosed attribute selector
$.isSelector("* []") = return false - empty attribute selector
$.isSelector("* [name]") = return true
$.isSelector("/hiThere") = return false - invalid / character
$.isSelector("body > ") = return false - > without following child selector
$.isSelector("body > [name=\\\[girls_just_want_to_have_fun\\\]].on a .beach") = return true
Probably there's an internal jQuery function that does the check (or a RegExp), but my voodoo is too poor to find it.
Probably something like this:
function isSelector(string)
{
try
{
$(string);
return true;
}
catch(e)
{
return false;
}
}
would do the trick, but it seems a little extreme.
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。几乎任何东西都可以是选择器,例如我的页面可能由一堆
blah
组成,这将使$("blah")
完全有效。jQuery 确实会对您作为参数传递的字符串进行一些检查,这发生在核心的
init
方法中,我在源浏览器中为您突出显示了该方法:https://github.com/jquery/jquery/blob/master/src/core.js#L78-186
You can't. Just about anything can be a selector, for example my page could consist of a bunch of
blah
s, which would make$("blah")
perfectly valid.jQuery does do some checking on the string you pass as argument, this happens within the
init
method of the core, which I have highlighted in source browser for you:https://github.com/jquery/jquery/blob/master/src/core.js#L78-186
我使用了这个解决方案:
此外,这个(有效)示例
返回 true
I've used this solution:
Additionally, this (valid) example
returns true