简体   繁体   English

如何将此 jquery 代码转换为 JavaScript?

[英]How do I convert this jquery code to JavaScript?

This is the jquery code below:这是下面的jquery代码:

$('div').on('click', function() {
 $(this).toggleClass('show-description');
});

I want to convert it to JavaScript because I get this error message:我想将其转换为 JavaScript,因为我收到此错误消息:

"$ is undefined " “$ 未定义”

when I put the jquery code in the JavaScript section of codepen.io.当我将 jquery 代码放在 codepen.io 的 JavaScript 部分时。

Is there a reason the jquery code is producing an error? jquery 代码是否有产生错误的原因? How can I fix this?我怎样才能解决这个问题? If it is not possible to fix, how can I convert the Jquery code to JavaScript?如果无法修复,如何将 Jquery 代码转换为 JavaScript?

I'm trying to use toggleClass on all the divs when the div is clicked.单击 div 时,我试图在所有 div 上使用 toggleClass。

Here is a link to the codepen for reference: https://codepen.io/sophiesucode/pen/jOExXKw这里是 codepen 的链接以供参考: https ://codepen.io/sophiesucode/pen/jOExXKw

  • Option 1: Use should push the jquery lib above </body> , Here is your demo选项 1:使用应该将 jquery 库推送到</body>之上,是您的演示
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • Option 2: Use pure javascript like below选项 2:使用纯 javascript,如下所示
document.querySelector('div').onclick = function(){
  this.classList.toggle("show-description");
};
$('div').on('click', function() {
 $(this).toggleClass('show-description');
});

Can be represented by vanilla javascript as:可以用 vanilla javascript 表示为:

var divs = document.querySelectorAll('div'); //Get a list of all div elements
for (const div of divs){ //Loops through every div element
    div.onclick = function(e) {  //Adds the on click function to each
        e.currentTarget.classList.toggle('show-description'); //Defines the function as toggling a class on the element of the click function
    }
}

Jquery code actually is javascript. Jquery 代码实际上是 javascript。 Jquery is a library built for javascript. Jquery 是一个为 javascript 构建的库。 To solve the error "$ is undefined" you would have to add jquery to your webpage, or import it in your script.要解决错误“$ 未定义”,您必须将 jquery 添加到您的网页,或将其导入您的脚本中。

There is this wonderful article on W3 Schools which teaches multiple ways to add jquery to your webpages. W3 Schools 上一篇精彩的文章,其中介绍了将 jquery 添加到网页的多种方法。

Your code doesn't work because you linked your script path as a relative path.您的代码不起作用,因为您将脚本路径链接为相对路径。

Change this <script src="/assets/jquery.js"></script>改变这个<script src="/assets/jquery.js"></script>

into this <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>进入这个<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

another way is to link the jquery file using the settings menu in codepen.另一种方法是使用 codepen 中的设置菜单链接 jquery 文件。

Settings > Javascript > then search jquery in the CDNsearch bar设置 > Javascript > 然后在 CDN 搜索栏中搜索 jquery

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM