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

$('element').length;

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


当前回答

最短的方法之一就是将下面的代码复制粘贴到控制台。

var jquery = document.createElement('script'); 
jquery.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.head.appendChild(jquery);

其他回答

我刚刚制作了一个带有错误处理的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...")}}})())

此处提供可读源代码

在控制台中运行

var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-3.4.1.min.js";document.getElementsByTagName('head')[0].appendChild(script);

它创建一个新的脚本标记,用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控制台片段中使用这个函数

由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();

交钥匙解决方案:

将代码放入code_here函数中。并防止没有HEAD标记的HTML。

(功能(头部){var jq=document.createElement('script');jq.src=“https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";((head&&head[0])||document.firstChild).appendChild(jq);})(document.getElementsByTagName('head'));函数jQueryReady(){if(window.jQuery){jQuery.noConflict();您的代码_此处(jQuery);}其他{setTimeout(jQueryReady,100);}}jQueryReady();函数yourCode_here($){console.log(“OK”);$(“body”).html(“<h1>你好!</h1>”);}