$(this).addClass()的一个注意点

本文记录了一个关于使用jQuery中addClass方法的常见误区:连续调用时类名被拼接而非覆盖的问题,导致元素类名出现预期之外的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在该公司项目里的一个bug时发现$(this).addClass("a");后再进行一次$(this).addClass("b"),则this元素的class为“a b”;,今天这个bug就是因为这个搞的许久。唉,写出来,让自己长长记性。

// 创建文件项 createFileItem() { this.$item = $(` <div class="file-item"> <div class="d-flex justify-content-between"> <span>${this.file.name}</span> <div class="btn-group"> <button class="btn btn-sm btn-secondary pause">暂停</button> <button class="btn btn-sm btn-danger cancel">取消</button> </div> </div> <div class="progress"> <div class="progress-bar" role="progressbar" style="width: 0%"></div> </div> <div class="status"></div> </div> `); this.$item.find('.pause').click(() => this.togglePause()); this.$item.find('.cancel').click(() => this.cancel()); $('#fileList').append(this.$item); } // 其他辅助方法 prepareChunks() { let offset = 0; while (offset < this.file.size) { this.chunks.push(this.file.slice(offset, offset + this.chunkSize)); offset += this.chunkSize; } } updateProgress() { const progress = (1 - this.missingChunks.length / this.chunks.length) * 100; this.$item.find('.progress-bar').css('width', `${progress}%`); } updateStatus(text) { this.$item.find('.status').text(text); } togglePause() { this.isPaused = !this.isPaused; this.$item.find('.pause').text(this.isPaused ? '继续' : '暂停'); if (!this.isPaused) this.uploadChunks(); } cancel() { this.isPaused = true; if (this.xhr) this.xhr.abort(); this.$item.remove(); } } // 初始化拖放功能 $(function() { const $dropZone = $('#dropZone'); const $fileInput = $('#fileInput'); // 拖放事件处理 $dropZone.on('dragover', e => { e.preventDefault(); $dropZone.addClass('dragover'); }).on('dragleave drop', e => { e.preventDefault(); $dropZone.removeClass('dragover'); }).on('drop', e => { handleFiles(e.originalEvent.dataTransfer.files); }); // 文件选择处理 $fileInput.change(e => handleFiles(e.target.files)); }); function handleFiles(files) { Array.from(files).forEach(file => { new ChunkedUploader(file); });帮我注释一下我要学习参考的
最新发布
03-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值