保存和调用 jQuery 选择器
我有一个应用程序可以保存单击的 jQuery 选择器以供以后使用,当我尝试调用该选择器时,我遇到了一个有趣的问题。下面是我的代码供参考。这是 AJAX 调用的回调函数,返回保存在 data
中的 JSON 对象。我已经验证数据传输正确,但似乎再次尝试使用字符串作为 jQuery 中的选择器不起作用。 String()
的东西只是为了测试,我不确定它是否有必要。
如果有人对为什么这可能不起作用有任何指导,我很想知道。任何带有 jQuery(selector)
的代码都不起作用。
jQuery.each(data.dot_collection, function() {
x_coord = this.x_coord;
y_coord = this.y_coord;
selector = new String(this.selector);
//Works
alert( selector ); // = html > body.home.blog.logged-in.single-author.two-column.right-sidebar > div.hfeed > header#branding > hgroup > h1#site-title
//Works
alert(jQuery("html > body.home.blog.logged-in.single-author.two-column.right-sidebar > div.hfeed > header#branding > hgroup > h1#site-title").offset().left);
// Not Working & jQuery(selector).offset() = 'undefined'
alert( jQuery(selector).offset().left );
I have an application that saves a clicked on jQuery selector for later use and I am running into a funny issue when I try and recall the selector. Below is my code for reference. This is a callback function for an AJAX call that returns a JSON object saved in data
. I have verified that the data is getting transfered correctly but it seems like trying to use the string as a selector in jQuery again doesn't work. The String()
stuff is just for a test and I am not sure it is necessary.
If anyone has any guidance on why this might not be working I would love to know. Any code with jQuery(selector)
just does not function.
jQuery.each(data.dot_collection, function() {
x_coord = this.x_coord;
y_coord = this.y_coord;
selector = new String(this.selector);
//Works
alert( selector ); // = html > body.home.blog.logged-in.single-author.two-column.right-sidebar > div.hfeed > header#branding > hgroup > h1#site-title
//Works
alert(jQuery("html > body.home.blog.logged-in.single-author.two-column.right-sidebar > div.hfeed > header#branding > hgroup > h1#site-title").offset().left);
// Not Working & jQuery(selector).offset() = 'undefined'
alert( jQuery(selector).offset().left );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设问题是您传递的是
String
object 而不是 原始字符串 并且 jQuery 无法检测到这一点。尝试:
I assume the problem is that you are passing a
String
object instead of a primitive string and jQuery cannot detect this.Try:
通过使用这个,我可以得到每个 p 的左偏移量(在你的例子中是集合)。
By using this, I can get offset left for each p (collection in your case).