jQuery add/remove class using 'this'
jQuery add/remove class using 'this'
我试图在div点击时将一个类附加到它,并在它第二次点击时删除它。我现在有我的脚本-
$(".project").click(function(){
if ($(".project-expand", this).is(':visible')) {
$(".project-expand",this).hide(1000);
$('.project').delay(1000).queue(function(){
$(".project").removeClass('item-dropped').clearQueue();
});
} else if ($(".project-expand", this).is(':hidden')) {
$(".project-expand").hide(1000);
$(".project-expand",this).show(1000);
$(".project").addClass('item-dropped');
}
});
但是,当我将代码更改为-时,这会将"item droped"类添加到所有具有类"project"的div中
$(".project", this).addClass('item-dropped');
它什么都没用,我哪里错了?
不用类选择器$('.project')
,只需使用点击事件的目标($(this)
):
$(".project").click(function () {
var project = $(this);
var projectExpand = $(".project-expand", this);
if (projectExpand.is(':visible')) {
projectExpand.hide(1000);
project.delay(1000).queue(function () {
project.removeClass('item-dropped').clearQueue();
});
} else if (projectExpand.is(':hidden')) {
$(".project-expand").hide(1000);
projectExpand.show(1000);
project.addClass('item-dropped');
}
});
其他信息:您尝试执行的操作最初不起作用的原因是,$('.project', this)
在当前元素中查找类为project
的元素(即在项目中查找项目)
您必须使用$(this)在单击的项目上添加类:
$(".project").click(function(){
if ($(".project-expand", this).is(':visible')) {
$(".project-expand",this).hide(1000);
$(this).delay(1000).queue(function(){
$(this).removeClass('item-dropped').clearQueue(); // Here
});
} else if ($(".project-expand", this).is(':hidden')) {
$(".project-expand").hide(1000);
$(".project-expand",this).show(1000);
$(this).addClass('item-dropped'); // Here
}
});
您必须使用:
$(this).addClass('item-dropped');
概念小提琴
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 如何通过引用var Using DataTables来进行分页或排序
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- Object.prototype using 'this'
- Javascript Object - using jQuery and this
- Jquery Options using $(this)
- Using this.selectedIndex inside an array in an 'onchange
- Using $(this).find with .click() jQuery
- jQuery add/remove class using 'this'
- Using `this` vs Object.create(prototype)
- Jquery - Using a function with .click and 'this'
- AngularJS using bind(this)
- Using function使用'this'关键字没有按预期工作
- Using "this" in Javascript
- using this.props.someVariable