您能否看一下这个演示,让我知道为什么我无法动态地将.red
添加到.ew-num
$(".ew-increaser").on("click", function(){
console.log("Clicked");
$(this).parent().prev(".ew-num").addClass('red');
$(this).parent().find(".ew-num").addClass('red');
$(this).parent().prev("ew-num").addClass('red');
$(this).parent().find("ew-num").addClass('red');
});
body{
padding:30px;
}
.red{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-decreaser">Left</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-num">Middle</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-increaser">Right</button>
</div>
</div>
</div>
答案 0 :(得分:1)
您需要定位parent()
的{{1}}兄弟姐妹的孩子
prev()
$(".ew-increaser").on("click", function() {
$(this).parent().prev().children(".ew-num").addClass('red');
});
.red {
color: red!important;
}
答案 1 :(得分:0)
尝试以下操作:-您应该使用children()
来获取父级div
子元素
$(".ew-increaser").on("click", function(){
console.log("Clicked");
$(this).parent().prev().children(".ew-num").addClass('red');
});
body{
padding:30px;
}
.red{
background:red!important;;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-decreaser">Left</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-num">Middle</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default ew-increaser">Right</button>
</div>
</div>
</div>