如何将这个jquery代码转换为JavaScript?

问题描述 投票:-3回答:3

这是下面的jquery代码:

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

我想将其转换为JavaScript,因为收到此错误消息:

“ $未定义”

当我将jquery代码放在codepen.io的JavaScript部分中时。

jquery代码产生错误是有原因的吗?我怎样才能解决这个问题?如果无法修复,如何将Jquery代码转换为JavaScript?

单击div时,我试图在所有div上使用toggleClass。

这里是指向密码笔的链接以供参考:https://codepen.io/sophiesucode/pen/jOExXKw

javascript jquery onclicklistener
3个回答
1
投票
  • 选项1:使用应将jquery lib推到</body>之上,Here是您的演示
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • 选项2:使用如下所示的纯JavaScript
document.querySelector('div').onclick = function(){
  this.classList.toggle("show-description");
};

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

可以用香草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代码实际上是javascript。 jQuery是为javascript构建的库。要解决错误“ $ is undefined”,您必须将jquery添加到您的网页,或将其导入脚本中。

[wonderful article on W3 Schools教了多种将jquery添加到您的网页的方法。


0
投票

您的代码无效,因为您将脚本路径链接为相对路径。

更改此<script src="/assets/jquery.js"></script>

进入此<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

另一种方法是使用codepen中的设置菜单链接jquery文件。

[设置> Javascript>然后在CDNsearch栏中搜索jquery

© www.soinside.com 2019 - 2024. All rights reserved.