确定字符串是否是有效的jQuery选择器? [英] Determine if a string is a valid jQuery selector?

查看:80
本文介绍了确定字符串是否是有效的jQuery选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery是否有一个方法来确定传递给函数的参数是否是一个选择器?

Does jQuery have a method to determine if an argument passed to function is a selector?

我正在为一些jQuery插件制作模板,我需要能够检查传入的参数是否是jQuery选择器。我想允许其他数据类型,并根据传递的数据类型执行不同的方法。检测数据类型很简单,但选择器只是一个字符串,可以通过多种不同方式构建。

I am making a template for some jQuery plugins and I need to be able to check if the argument passed in is a jQuery selector. I want to allow for other data types and perform different methods based on what data type is passed. Detecting data types is easy, but selectors are just a string and can be constructed is many different ways.

我的目标是创建对你传入的内容宽容的插件争论并做出有关如何处理的有根据的决定。以jQuery UI插件为例,在一些插件中,假设我们在参数占位符中传递一个回调函数,该函数用于速度的数字,它仍然需要回调并运行它并使用默认的速度。这就是我想要的功能和选择器是一个非常独特的案例。

My goal is to create plugins that are forgiving with what you pass in for the arguments and makes educated decisions about what to do with it. Take the jQuery UI plugins for example, in some plugins, lets say we pass a callback function in the argument place holder that is for a number for a speed, it still takes the callback and runs it and uses the default for speed. That's the kind of functionality I'm going for and selectors are a pretty unique case.

jQuery是否为此编写了一个正则表达式?我在代码中找不到一个。

Has jQuery written a Regex for this? I couldn't find one in the code.

如果没有,我想我只需要写一个巨大的正则表达式吗?

If not, I guess I'll just have to write a huge Regex for this?

推荐答案

很多字符串技术上可以是 $('blah')可以选择自定义元素!没有任何好的方法可以知道 intent 如何处理传递给你的函数的参数,所以最好有一个像Gaby评论的定义良好的结构。

Lots of strings can technically be a selector like $('blah') could select custom elements! There isn't any good way of knowing the intent of what to do with the argument passed to your function, so it's best to have a well defined structure like Gaby has commented.

选择器:

yourFunction({ selector: 'div' });

yourFunction({ value: 'testing' });

在您的代码中采用不同的路线。

Will take a different route in your code.

如果没有这种技术,你可以做的最好就是尝试jQuery根据选择器查找元素,检查 .length ,如果找到元素则假设调用者想要一个jQuery选择器。另一种选择可能只是记录必须传递jQuery对象,即:

Without this technique the best you can do is just attempt for jQuery to find elements based on the selector, check with .length, if elements are found then assume the caller intended a jQuery selector. Another option could be just to document that a jQuery object must be passed i.e.:

yourFunction({ value: jQuery('div') });

然后您可以使用其他路线

Then for a different route you can do

if (value instanceof of jQuery) { .... }

这篇关于确定字符串是否是有效的jQuery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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