对于不使用jQuery的网站,有没有一种简单的方法将jQuery包含在Chrome JavaScript控制台中?例如,在一个网站上,我想获取表中的行数。我知道jQuery很容易做到这一点。

$('element').length;

该网站不使用jQuery。我可以从命令行添加它吗?


当前回答

我已经在公认的解决方案基础上进行了改进

var also_unconflict = typeof $ != "undefined";

var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

if(also_unconflict){
    setTimeout(function(){
        $=jQuery.noConflict();
        console.log('jquery loaded, use jQuery instead of $')
    }, 500)
}else{
    console.log('jquery loaded, you can use $');
}

我在googlechrome控制台片段中使用这个函数

其他回答

以下是替代代码:

javascript:(function() {var url = '//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; var n=document.createElement('script');n.setAttribute('language','JavaScript');n.setAttribute('src',url+'?rand='+new Date().getTime());document.body.appendChild(n);})();

它可以直接在Console中粘贴,也可以创建一个新的书签页面(在Chrome中,右键单击书签栏,添加页面…)并将此代码粘贴为URL。

要测试这是否有效,请参见下文。

之前:

$()
Uncaught TypeError: $ is not a function(…)

之后:

$()
[]

FWIW,Firebug嵌入include特殊命令,jquery默认为别名:https://getfirebug.com/wiki/index.php/Include

因此,在您的情况下,您只需键入:

include("jquery");

弗洛朗

由jondavidjohn给出的最佳答案很好,但我想对其进行调整,以解决以下几点:

各种浏览器在将脚本从http加载到https页面时发出警告。如果您直接从浏览器的URL栏尝试,只需将jquery.com的协议更改为https,就会收到警告:这可能不是您要查找的站点!当我使用控制台尝试Gmail等谷歌网站时,我喜欢使用谷歌的CDN。

我唯一的问题是,我必须在控制台中包含一个版本号,我总是想要最新版本。

var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();

我刚刚制作了一个带有错误处理的jQuery3.2.1书签(如果尚未加载,则仅加载,如果已加载,则检测版本,如果加载时出错,则显示错误消息)。在Chrome 27中测试。没有理由在Chrome浏览器上使用“旧”jQuery 1.9.1,因为jQuery 2.0与1.9兼容。

只需在Chrome的开发者控制台中运行以下命令或将其拖放到书签栏中:

javascript:((function(){if(typeof(jQuery)=="undefined"){window.jQuery="loading";var a=document.createElement("script");a.type="text/javascript";a.src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";a.onload=function(){console.log("jQuery "+jQuery.fn.jquery+" loaded successfully.")};a.onerror=function(){delete jQuery;alert("Error while loading jQuery!")};document.getElementsByTagName("head")[0].appendChild(a)}else{if(typeof(jQuery)=="function"){alert("jQuery ("+jQuery.fn.jquery+") is already loaded!")}else{alert("jQuery is already loading...")}}})())

此处提供可读源代码

这个答案基于@genesis答案,起初我尝试了书签版本@jondavidjohn,但它不起作用,所以我将其更改为这个(将其添加到书签中):

javascript:(function(){var s = document.createElement('script');s.src = "//code.jquery.com/jquery-2.2.4.min.js";document.getElementsByTagName('head')[0].appendChild(s);console.log('jquery loaded')}());

警告语,没有在chrome中测试,但在firefox中有效,也没有在冲突环境中测试。