gpt4 book ai didi

javascript - 无法让这个基本的toggleClass在JQuery中工作

转载 作者:行者123 更新时间:2023-12-02 14:40:01 27 4
gpt4 key购买 nike

所以我不确定我做错了什么。我试图通过在单击按钮时切换类来使按钮看起来好像被按下一样。

我做了一个快速的 JavaScript if 语句来确保 jQuery 已加载。

这是代码:

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.12.3.min.js"></script>
<script>
$("button").click(function(){
$("button").toggleClass("active-class");
});
</script>
<style type="text/css">
.active-class {
background-color:red;
}

/* Non-important styles */
button {
font-size:15px;
padding:10px;
background-color:#E8E8E8;
border:1px solid rgba(0,0,0,0.3);
border-radius:5px;
outline:none;
}
</style>
</head>
<body>
<button>Click to toggle!</button>



</body>
</html>

当我点击按钮时,它什么也没做。有什么建议吗?

最佳答案

将 js 移到结束正文标记之前。或添加文档准备功能:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script>
$( document ).ready(function() {
$("button").click(function(){
$("button").toggleClass("active-class");
});
});
</script>
<style type="text/css">
.active-class {
background-color:red;
}
/* Non-important styles */
button {
font-size:15px;
padding:10px;
background-color:#E8E8E8;
border:1px solid rgba(0,0,0,0.3);
border-radius:5px;
outline:none;
}
</style>
</head>
<body>
<button>Click to toggle!</button>
</body>
</html>

关于javascript - 无法让这个基本的toggleClass在JQuery中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093387/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com