所以我正忙着创建一个迷你网店,我正在使用谷歌的前端 ( MDL ) 模板
我想在我的网上商店做的是,当用户点击 x 产品时,我想切换一个类,
我在循环内使用闭包来检测对任何产品的点击。
我唯一的问题是,课程不会切换。我尝试使用 addClass 确实有效,但它不那么方便,因为我真的想切换类(从选定产品到未选定)
看看我的代码片段,你就会明白,你会看到我确实正确地检测到了点击。但是切换类不起作用。
$(document).ready(function() {
console.log("Document ready");
for (var i = 1; i < $(".products").length; i++) {
(function(index){
$(".products").click(
function(e){
console.log("click successfull!");
console.log(this);
$(this).css("border", "1px solid #1976D2");
$(this).toggleClass("mdl-shadow--16dp");
});
})(i);
}
$("#Card").keyup(function(event){
if(event.keyCode == 84){
console.log("Class toggled!");
$(".products").toggleClass("mdl-shadow--2dp mdl-shadow--16dp");
}
});
});
.mdl-card__actions{
display: flex;
box-sizing:border-box;
align-items: center;
}
.page-content .mdl-card {
display: inline-block;
margin: 5px 5px 5px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.indigo-pink.min.css">
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="page-content">
<!-- Your content goes here -->
<div class="mdl-card mdl-shadow--2dp products">
<div class="mdl-card__title">
<h2 class="mdl-card__title-text">Dell XP13 </h2>
</div>
<img src="https://goo.gl/gDDH0i" alt="dell xp13">
<div class="mdl-card__supporting-text"><b>Basisprijs: 1.649,00$<b></div>
<div class="mdl-card__actions mdl-card--border">
<a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
Add to cart
</a>
<div class="mdl-layout-spacer"></div>
<i class="material-icons">add_shopping_cart</i>
</div>
</div>
<div class="mdl-card mdl-shadow--2dp products">
<div class="mdl-card__title">
<h2 class="mdl-card__title-text">Chromebook pixel2</h2>
</div>
<img src="https://goo.gl/pNie9C.png" alt="chrombook">
<div class="mdl-card__supporting-text"><b>Basisprijs: 999,99$<b></div>
<div class="mdl-card__actions mdl-card--border">
<a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
Add to cart
</a>
<div class="mdl-layout-spacer"></div>
<i class="material-icons">add_shopping_cart</i>
</div>
</div>
<div class="mdl-card mdl-shadow--2dp products">
<div class="mdl-card__title">
<h2 class="mdl-card__title-text">Macbook 13'</h2>
</div>
<img src="https://goo.gl/qzq0Cr" alt="Macbook">
<div class="mdl-card__supporting-text"><b>Basisprijs: 1.129,00$<b></div>
<div class="mdl-card__actioder">
<a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
Add to cart
</a>
<div class="mdl-layout-spacer"></div>
<i class="material-icons">add_shopping_cart</i>
</div>
</div>
</div>
</body>
我将在一个单独的链接中向您展示我正在切换的效果,在这个链接中,我正在切换所有“div”的效果,但我不会每次点击。