昨晚我花了几个小时试图找出这里出了什么问题,但没有成功。 我有一个 div,单击它会展开并创建一个关闭按钮,该按钮会将 div 返回到其原始状态。我通过添加和删除类来做到这一点。我遇到的问题是,当单击原始 div (.talent) 时,它确实会更改以填充包含的 div。但是,当单击按钮 (.btn) 时,div 不会返回到其原始状态。
JS-
$(".talents .talent").click(function(){
if ($(this).hasClass("talent")) {
$(this)
.removeClass("talent")
.addClass("tree")
.append("<div class=\"close btn\">X</div>");
$(".tree .btn").click(function(){
console.debug("WORKING!?!?!?");
$(".tree").addClass("talent");
$(".tree").removeClass("tree");
$(".talents .talent").show();
$(this).remove();
});
$(".talents .talent").hide();
}
});
CSS -
.talents{
border:1px solid white;
border-radius:10px;
overflow:hidden;
height:165px;
margin:10px;
}
.talents .talent{
text-align:center;
font-size:2.4em;
height: 50px;
width: 50px;
background-repeat: no-repeat;
background-position: center;
background-size: 100% 100%;
display: inline-block;
border: 3px solid white;
border-radius: 15px;
margin: 5px 7px 5px 7px;
}
.tree{
position:relative;
width:100%;
height:100%;
}
最佳答案
$(".talents .talent").click(function(){
if ($(this).hasClass("talent")) {
以上代码的计算结果总是为真
如果你想让它更好地工作,任何具有人才等级的元素也应该有另一个等级,并且像这样工作(我会说使用 .tree 作为 .other_class 但如果没有看到 html 就不能 100% 确定):
$(".talents .other_class").click(function(){
if ($(this).hasClass("talent")) {
另外,最好将 btn 点击处理程序放在第一个点击处理程序之外。
关于javascript - .addClass().removeClass() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18086157/