为什么说未定义$?

时间:2019-01-05 18:40:50

标签: jquery html css

因此,因为我希望组织代码,所以我在互联网上搜索了如何将jQuery加载到JS文件中,以便可以将该JS文件加载到html文件中并可以在JS文件中单独工作。我在网上找到了一个优雅的解决方案,并应用了它,当我检查是否已加载jQuery时,它可以工作,但是当我尝试从div中查找类时,它就无法工作。它给了我“ $未定义”错误。为什么?检查显示jQuery已加载。

JS代码:

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
window.onload = function()
{
if (window.jQuery)
{
    alert('jQuery is loaded');
}
else
{
    alert('jQuery is not loaded');
}
}
$('.spectacle').click(function(){
alert('plm');
});

HTML代码:

<!DOCTYPE html>
<html>
<head>
<title>Spectacole</title>
<link rel="stylesheet" type="text/css" href="Spectacole.css">
</head>
<body>
<div id="top-bar">
    <div id="bar-background"></div>
    <a href="../StartingPage/startingPage.html"><button 
id="mainMenu">
    </button></a>
</div>
<div id="wrapper">
    <div class="spectacle">

    </div>

    <div class="spectacle">

    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
</div>
    <script type="text/javascript" src="Spectacole.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

添加

$('.spectacle').click(function(){
alert('plm');
});

window.onload = function(){ }

 var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
window.onload = function()
{
if (window.jQuery)
{
    alert('jQuery is loaded');
}
else
{
    alert('jQuery is not loaded');
}
  $('.spectacle').click(function(){
alert('plm');
});
}
.spectacle {
  height:50px;
  width:50px;
  background:#000;
  border:1px solid #fff;
}
<!DOCTYPE html>
<html>
<head>
<title>Spectacole</title>
<link rel="stylesheet" type="text/css" href="Spectacole.css">
</head>
<body>
<div id="top-bar">
    <div id="bar-background"></div>
    <a href="../StartingPage/startingPage.html"><button 
id="mainMenu">
    </button></a>
</div>
<div id="wrapper">
    <div class="spectacle">

    </div>

    <div class="spectacle">

    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
    <div class="spectacle">
    </div>
</div>
    <script type="text/javascript" src="Spectacole.js"></script>
</body>
</html>

答案 1 :(得分:1)

为什么要通过将脚本标签附加到DOM来添加jQuery,为什么不只是将标签放在DOM中呢?

似乎与本SO中讨论的问题相同:Load jQuery with Javascript and use jQuery