【发布时间】:2018-04-02 00:35:50
【问题描述】:
为什么要让这个 jQuery 代码工作需要两次点击按钮? 浏览器加载此文件并加载脚本标记存在于 head 部分。但是此代码仅在单击 2 次后才有效。
function j1() {
$("button").click(function() {
$("p").hide();
});
}
function load1() {
var target = document.getElementsByTagName("head");
var newScript = document.createElement("script");
var url =
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
newScript.src = url;
target[0].appendChild(newScript);
newScript = document.createElement("script");
url = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
newScript.src = url;
target[0].insertBefore(newScript, target[0].firstChild);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="load1();">
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button onclick="j1();">Click me</button>
</body>
</html>
【问题讨论】:
-
你调试过你的代码吗?在 j1() 的第一行设置断点。
-
我没有 JS 的调试器,但我检查得很彻底。我也在运行它并使用 Chrome “inspect”对其进行检查。
-
我能够将 JQuery 动态添加到 或 HTML(在浏览器检查中看到),但需要两次调用 J1() 才能让 JQuery 完成工作。顺便说一句,在 load1() 中调用 J1() 也不起作用。
标签: javascript jquery