简体   繁体   English

jQuery选择器在控制台中不起作用

[英]jQuery selectors don't work in console

I can't for the life of me work this one out. 我不能为我的生活工作这一个。 I have js running and 'container state..' is a console log from the running js on the page. 我有js正在运行,'container state ..'是来自页面上运行的js的控制台日志。 It's displaying a selector, but if i want to do anything within the console it just returns null. 它正在显示一个选择器,但如果我想在控制台中做任何事情,它只返回null。 I'm assuming somehow i'm over writing jQuery function somewhere, as if i called jQuery 我假设某种程度上我在某处编写jQuery函数,好像我调用了jQuery

>>> $
function()

This is how i am calling a selector 这就是我调用选择器的方式

Container state 3 jQuery(div.module-carousel)
>>> $('body')
null  

jQuery uses 2 namespaces, jQuery and $ . jQuery使用2个命名空间, jQuery$ Another library could have used the $ . 另一个图书馆可以使用$ Try using jQuery instead of $ (assuming that it isn't overridden as well): 尝试使用jQuery而不是$ (假设它也没有被覆盖):

jQuery('body');

or wrap jQuery in an immediate function and use $ in it so you don't need to replace $ in the existing code: 或者在一个立即函数中包装jQuery并在其中使用$ ,这样你就不需要在现有代码中替换$

(function($){
    //"$" in here is jQuery
    //code that uses $ as jQuery will work in here
}(jQuery)); //pass in jQuery and execute

你可以在控制台上编写任何命令之前使用它。

$ = jQuery.noConflict();

If your $ is overloaded (but not jQuery ), and you want to work in your console, just do the following: 如果你的$超载(但不是jQuery ),并且你想在你的控制台中工作,只需执行以下操作:

$ = jQuery;

As simple as that. 就如此容易。

For a more complete solution (real development, not just console), use @Joseph the Dreamer 's solution. 要获得更完整的解决方案(真正的开发,而不仅仅是控制台),请使用@Joseph the Dreamer的解决方案。

Both Firefox and Chrome define $ as a shorthand for document.getElementById in the console. Firefox和Chrome都将$定义为控制台中document.getElementById的简写。 This shorthand will automatically be overridden when the page defines $ . 当页面定义$时,将自动覆盖此简写。

So, load jQuery ( through a bookmarklet for example) and you can use jQuery selectors. 因此,加载jQuery(例如通过书签 ),您可以使用jQuery选择器。

If you don't need jQuery-specific selectors, you can also use $$ , which is a shorthand for document.querySelectorAll , which supports CSS(3) selectors. 如果您不需要特定于jQuery的选择器,您还可以使用$$ ,它是document.querySelectorAll的简写,它支持CSS(3)选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM