我是Javascript的新手,并且通过一些课程自学。我只是好奇我怎么能使下面的代码重复性降低?有没有办法以不同的方式处理以下问题,或者您会采用相同的方法吗?
var imgContainer = document.getElementById("imgContainer");
var lorem = document.querySelector(".hdr-left");
var ipsum = document.querySelector(".hdr-right");
//When clicking on imgContainer toggle between class to change colour and position
imgContainer.addEventListener('click', function() {
lorem.classList.toggle("hdr-color-white");
ipsum.classList.toggle("hdr-color-white");
lorem.classList.toggle('hdr-left-middle');
ipsum.classList.toggle('hdr-right-middle');
});
答案 0 :(得分:1)
一种方法是创建toggle
函数:
var imgContainer = document.getElementById("imgContainer");
var lorem = document.querySelector(".hdr-left");
var ipsum = document.querySelector(".hdr-right");
function toggle(el, className) {
el.classList.toggle(className);
}
//When clicking on imgContainer toggle between class to change colour and position
imgContainer.addEventListener('click', function() {
toggle(lorem, "hdr-color-white");
toggle(ipsum, "hdr-color-white");
toggle(lorem, 'hdr-left-middle');
toggle(ipsum, 'hdr-right-middle');
});
另一种方法是创建一系列运营数据:
var imgContainer = document.getElementById("imgContainer");
var lorem = document.querySelector(".hdr-left");
var ipsum = document.querySelector(".hdr-right");
toggleOps = [
{ el: lorem, name: 'hdr-color-white'},
{ el: ipsum, name: 'hdr-color-white'},
{ el: lorem, name: 'hdr-left-middle'},
{ el: ipsum, name: 'hdr-right-middle'}
]
//When clicking on imgContainer toggle between class to change colour and position
imgContainer.addEventListener('click', function() {
toggleOps.forEach( )
function(op) {
op.el.classList.toggle(op.name);
}
)
});
减少代码总是一件好事,除非减少使代码难以理解。
数据驱动代码非常棒,因为您可以添加更多数据而无需编写其他代码。
保持干燥(不要重复自己)是值得的。如果我写两次,我想重构将重复的代码移动到一个函数中。如果我需要第三次复制它,那么我会利用这段时间重构一个新函数并修复所有三个地方来调用该函数。
答案 1 :(得分:0)
你可以让方法做重复的工作:
var imgContainer = document.getElementById("imgContainer");
var lorem = document.querySelector(".hdr-left");
var ipsum = document.querySelector(".hdr-right");
//When clicking on imgContainer toggle between class to change colour and position
imgContainer.addEventListener('click', function() {
toggleClass(lorem.classList,"hdr-color-white");
// so on...
});
function toggleClass(elementClassList, className){
elementClassList.toggle(className);
}