Javascript动态加载jQuery库

时间:2017-10-20 19:14:05

标签: javascript jquery

为什么在按钮上点击两次才能使这个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>

3 个答案:

答案 0 :(得分:2)

.click()调用注册了一个新的点击监听器。因此,用户按下按钮一次以注册点击监听器,然后再次按下它以隐藏段落。

相反,只需删除onclick标记,然后使用.click()侦听器,反之亦然。

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);
  
  $("button").click(function() {
    $("p").hide();
  });
}
<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>Click me</button>

</body>

</html>

答案 1 :(得分:0)

我正在为这个问题添加一些细节......所以,正如你在下面看到的那样,我的小js文件被加载了,简单的函数在第一次点击时效果很好......这带回了原来的问题,为什么是JQuery当由Js代码加载时表现不同?

  function load2()
    {
        var target = document.getElementsByTagName("head");

    var newScript = document.createElement("script");
    var url = "js_libs/f1.js";
    newScript.src = url; 
    target[0].appendChild(newScript);
}




  <body onload="load1(); load2();" >


   <button onclick="f1();">Click me too</button>

答案 2 :(得分:0)

这个问题的解决方案是一个Stackoverflow问题......

https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#cv2.randu

这是解决问题的代码..

<script type='text/javascript'>
runScript();

function runScript() 
{
// Script that does something and depends on jQuery being there.
if( window.$ ) 
{
// do your action that depends on jQuery.
} 
else 
{
// wait 50 milliseconds and try again.
window.setTimeout( runScript, 50 );
}
}
</script>
相关问题