jQuery addClass方法为什么没有起作用?

clipboard.png
代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery.js"></script>
<style>
.menu{ width:20px; height:20px; background:red; position:relative;}
.menu div{border:3px red solid; width: 100px; height:100px; background:black; position:absolute; top:20px;}
.add_class{ border:3px blue solid;}
</style>
</head>

<body>
<div class="menu">
<div></div>
</div>
<script>
$(".menu").click(
 function(){
     $(".menu div").addClass("add_class")
     }
)
</script>
</body>
</html>
阅读 10.8k
4 个回答

楼上都不对。

其实 add_class 已被添加,只是由于 class 的优先级过低,新样式被忽略了。正确做法是:

.add_class{ border:3px blue solid!important;}

https://jsfiddle.net/hsfzxjy/...

可能是选择器问题,用$("div", $(this))或$(this).children("div")试试

把function去掉。 click已经是一个function了

function是多余的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进