当我单击具有类oldClass的单词Hello时,jquery将类更改为类newClass,该类为单词Hello blue着色。这意味着课程发生了变化。为什么jquery没有响应单击类newClass?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$(".oldClass").click(function(){
$(".oldClass").attr("class","newClass");
});
$(".newClass").click(function(){
$(".newClass").attr("class","oldClass");
});
});
</script>
<style>
.oldClass {color:red;}
.newClass {color:blue;}
</style>
</head>
<body>
<p class="oldClass">Hello</p>
</body>
答案 0 :(得分:4)
委派您点击活动
$('body').on('click','.oldClass',function(){
$(".oldClass").attr("class","newClass");
});
$('body').on('click','.newClass',function(){
$(".newClass").attr("class","oldClass");
});
最好使用toggleClass
$('body').on('click','.oldClass,.newClass',function(){
$(this).toggleClass('newClass oldClass');
});
答案 1 :(得分:1)
更好用 toggleClass('oldClass newClass');
答案 2 :(得分:0)
因为newClass在事件绑定时不存在。 每当更改类时,您都需要附加事件 使用以下代码
$(document).ready(function(){
function bindOldClassClick(){
$(".oldClass").click(function(){
$(".oldClass").attr("class","newClass");
bindNewClassClick();
});
}
function bindNewClassClick(){
$(".newClass").click(function(){
$(".newClass").attr("class","oldClass");
bindOldClassClick();
});
}
bindOldClassClick();
});
在jsfiddle上查看 https://jsfiddle.net/9w0z95ru/
答案 3 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style>
p{
cursor:pointer;
}
.newClass{
color: red;
}
.oldClass{
color: black;
}
</style>
<body>
<p class="oldClass">This is my paragraph - use me</p>
</body>
<script type="text/javascript">
// CHECK WHICH THE CLASS NAME AND CHANGE
$("p").click(function(){
var theClassname = $(this).attr('class');
if(theClassname == "oldClass")
{
$(this).attr('class','newClass');
}
else
{
$(this).attr('class','oldClass');
}
});
</script>
</html>
&#13;