jquery - 我怎样才能优化这个jquery?
问题描述
如果悬停另一个元素,我编写了一些 JS 代码来更改一个元素的 CSS 样式。我有 6 对元素。很明显,有更好的编码方式。请帮我。网站使用 Worpdress。
(function($) {
$(document).ready(function() {
$('.img-zink').hover(function() {
$('#btn-zink').attr('style', 'background-color: #4aab61; color: white !important');
}, function() {
$('#btn-zink').attr('style', '');
});
$('.img-rist').hover(function() {
$('#btn-rist').attr('style', 'background-color: #4aab61; color: white !important');
}, function() {
$('#btn-rist').attr('style', '');
});
$('.img-start').hover(function() {
$('#btn-start').attr('style', 'background-color: #4aab61; color: white !important');
}, function() {
$('#btn-start').attr('style', '');
});
$('.img-humat').hover(function() {
$('#btn-humat').attr('style', 'background-color: #4aab61; color: white !important');
}, function() {
$('#btn-humat').attr('style', '');
});
$('.img-bor').hover(function() {
$('#btn-bor').attr('style', 'background-color: #4aab61; color: white !important');
}, function() {
$('#btn-bor').attr('style', '');
});
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
解决方案
您可以添加以下CSS
.active {
background-color: #4aab61;
color: white !important;
}
然后像这样为一个hover()
函数中的所有元素切换类:
$('.img-zink, .img-rist, .img-start, .img-humat, .img-bor').hover(function() {
let className = $(this).attr("class").substr(3);
$('#btn' + className).toggleClass("active");
});
推荐阅读
- c# - 结合多种方法
- javascript - Javascript:Firefox中的问题与复选框+标签+ preventDefault
- django - 修复 Celery 问题“不能腌制”
: 内置的属性查找模块失败 - junit - 断言 null 不起作用,因为实际方法会更改值
- jquery - 使用jquery垂直旋转文本动画,一段时间后图像应该淡入淡出
- python - Python UTC 到本地
- java - 默认开启前置摄像头
- javascript - 我想在图像标签的路径中写图标名称
- javascript - 删除链式承诺
- angularjs - 在选择标签内添加一个额外的按钮作为选项,以便单击该按钮会打开另一个对话框