我正在尝试从头开始制作一个包含 5 个元素的 ScrollView ,我将 div 标签与 jQuery 和 CSS 类结合使用。
点击事件被触发但由于某种原因新类没有设置(圆圈应该是白色的)并且它恢复到它的默认颜色。
我正在使用 Bootstrap 3 和最新的 jQuery
HTML
<div class="row-fluid">
<div class="col-md-1"></div>
<div class="col-md-2">
<div class="circle 1" id="circle_1>
</div>
</div>
<div class="col-md-2">
<div class="circle 2" id="circle_2">
</div>
</div>
<div class="col-md-2">
<div class="circle 3" id="circle_3">
</div>
</div>
<div class="col-md-2">
<div class="circle 4" id="circle_4">
</div>
</div>
<div class="col-md-2">
<div class="circle 5" id="circle_5">
</div>
</div>
<div class="col-md-1"></div>
</div>
CSS
/* CSS used here will be applied after bootstrap.css */
.circle-selected{
border-radius: 50%;
width: 100px;
height: 100px;
background: #ffffff;
cursor: pointer;
}
.circle {
border-radius: 50%;
width: 100px;
height: 100px;
background: #949494;
-webkit-transition: all ease .3s;
-moz-transition: all ease .3s;
-o-transition: all ease .3s;
transition: all ease .3s;
font-family: 'Corbel Bold';
/* width and height can be anything, as long as they're equal */
}
.circle:hover{
border-radius: 50%;
width: 100px;
height: 100px;
background: #ffffff;
cursor: pointer;
}
jQuery
$(".circle").click(function(){
var ID = $(this).attr('class').replace('circle ', '');
//alert('called 1');
$("#circle_" + ID).addClass('circle ' + ID).removeClass('circle-selected ' + ID);
});
$(".circle-selected").click(function(){
var ID = $(this).attr('class').replace('circle-selected ', '');
//alert('called 2');
$("#circle_" + ID).addClass('circle-selected ' + ID).removeClass('circle ' + ID);
});
例子是最好的,所以这是我的:http://www.bootply.com/6qrSq5KvkK
有人可以指出我在这里做错了什么吗?我试过 .switchClass 但它不起作用,所以通过搜索 SO 我在这里找到了答案 jQuery UI switchClass() method is not working properly这表明我应该更换
.switchClass
与
addClass('square').removeClass('circle');
最佳答案
您不能在 ID 中使用空格。 jQuery 选择器会认为它是一个后代对象!
例子如果你有
<div class="ancestor">
<div class="child">
</div>
</div>
jQuery 子选择器
$(".ancestor .child")
空格表示后代对象。在您的例子中,jQuery 正在寻找一个对象 <3> 在一个 id 为 circle
的元素中来源:http://www.w3schools.com/cssref/css_selectors.asp
编辑:
您也不需要在类属性中添加 ID。愿它对你有用:
var ID = $.trim($(this).attr('class').replace('circle-selected', '').replace('circle', ''));
$("#circle_" + ID).toggleClass('circle').toggleClass('circle-selected');
查看此 JSFiddle
关于javascript - 单击时 jQuery 切换 div 类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27749788/