Man*_*ghe 3 javascript jquery addclass removeclass
我有两个班级空着色.一旦我点击了彩色类,然后删除彩色类并添加空类.我再次点击它应该添加彩色类和remoce空类.但它没有用.
var color_click = false;
var select_color = "";
$( ".colored").on('click',function(e){
if(color_click != true){
color_click = true;
select_color = $(this).css('background-color');
$(this).removeClass("colored");
$(this).addClass( "empty");
$(this).css('background-color','')
}
});
$( ".empty").click(function(){
if(color_click == true){
color_click = false;
$(this).css('background-color',select_color);
$(this).addClass("colored");
$(this).removeClass( "empty");
}
});
Run Code Online (Sandbox Code Playgroud)
是.那是因为您将事件绑定到该特定类.您可以使用事件委派来使用on()解决问题.当您的事件绑定发生时,该类没有元素,.empty绑定无效.而不是使用文档头(在我的示例中使用)使用始终存在于DOM中的容器并保存此元素.因此,通过事件委派,您实际上将事件绑定到容器/文档头,以便对现在以及将来存在于DOM中的元素进行委派.
除此之外,我做了一些更改,以删除一些模糊的检查和使用链接.
$(document).on('click', ".colored", function(e){
if(!color_click){ // You dont need this check if your variable is modified only in these 2 events
color_click = true;
select_color = $(this).css('background-color');
$(this).removeClass("colored").addClass( "empty").css('background-color','');
}
});
$( document).on('click', ".empty", function(){
if(color_click){// You dont need this check if your variable is modified only in these 2 events
color_click = false;
$(this).addClass("colored").removeClass("empty").css('background-color',select_color);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3393 次 |
| 最近记录: |