1 回答
TA贡献1895条经验 获得超7个赞
您在多个地方使用相同的 id,这是行不通的,因为 id 属性必须是唯一的,而且 css 类.ui-selected需要更具体。
至于事件侦听器,您可以change向复选框添加侦听器并使用 jQuery.closest()方法查找父卡。
这是一个简短的 jQuery 工作示例:
$(() => {
$("input[type=checkbox]").on("change", e => {
$(e.target).closest(".card").toggleClass("ui-selected")
})
})
.cards-wrapper {
display: flex;
flex-wrap: wrap;
columns: 4;
}
.cards-wrapper .card {
flex-grow: 1;
margin: 10px;
width: 150px;
}
.card.ui-selected { /* This selector must be more specific */
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<section class="container-lg">
<div class="cards-wrapper" id="card-div-wrapper">
<div class="card">
<div class="card-header">
<span>Sample Title</span>
<span style="float: right;"><input type="checkbox"></span>
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Sample Title</span>
<span style="float: right;"><input type="checkbox"></span>
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Sample Title</span>
<span style="float: right;"><input type="checkbox"></span>
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<div class="card">
<div class="card-header">
<span>Sample Title</span>
<span style="float: right;"><input type="checkbox"></span>
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</section>
- 1 回答
- 0 关注
- 80 浏览
添加回答
举报