我有一个非常简单的问题:我的代码太重复了。它有效,但我敢肯定它可能会干净得多,但我不知道从哪里开始。
我想学习更好地工作,我真的很想有人帮助我。
这是我的代码中非常重复的 2 位(我自己做过的所有事情):
$(document).ready(function(){
// Setup your Lazy Line element.
// see README file for more settings
$('#drawing1').lazylinepainter({
'svgData' : dr1,
'strokeWidth':1.2,
'strokeColor':'#65615a',
'onComplete' : function(){
}
})
$('#drawing2').lazylinepainter({
'svgData' : dr2,
'strokeWidth':1.2,
'strokeColor':'#65615a',
'onComplete' : function(){
}
})
$('#drawing3').lazylinepainter({
'svgData' : dr3,
'strokeWidth':1.2,
'strokeColor':'#65615a',
'onComplete' : function(){
}
})
$('#drawing4').lazylinepainter({
'svgData' : dr4,
'strokeWidth':1.2,
'strokeColor':'#65615a',
'onComplete' : function(){
}
})
$('#drawing5').lazylinepainter({
'svgData' : dr5,
'strokeWidth':1.2,
'strokeColor':'#65615a',
'onComplete' : function(){
}
})
// Paint your Lazy Line, that easy!
})
})( jQuery );
代码的第二部分:
var eventsFiredDr1 = 0;
var drawing1 = function() {
if (eventsFiredDr1 == 0) {
$('#drawing1').lazylinepainter('paint');
eventsFiredDr1++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr2 = 0;
var drawing2 = function() {
if (eventsFiredDr2 == 0) {
$('#drawing2').lazylinepainter('paint');
eventsFiredDr2++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr3 = 0;
var drawing3 = function() {
if (eventsFiredDr3 == 0) {
$('#drawing3').lazylinepainter('paint');
eventsFiredDr3++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr4 = 0;
var drawing4 = function() {
if (eventsFiredDr4 == 0) {
$('#drawing4').lazylinepainter('paint');
eventsFiredDr4++; // <-- now equals 1, won't fire again until reload
}
}
var drawing5 = function() {
if (eventsFiredDr5 == 0) {
$('#drawing5').lazylinepainter('paint');
eventsFiredDr5++; // <-- now equals 1, won't fire again until reload
}
}
$(window).resize(function() {
if ($(window).width() < 820) {
$("svg").hide()
$(".fallback").show()
$("#drawing2").css("height", "auto")
}
});
if ($(window).width() > 820 ) {
$(".fallback").hide()
$(window).scrollStopped(function(){
if ($("#drawing1").is(":within-viewport")) {
drawing1()
}
if ($("#drawing2").is(":within-viewport")) {
drawing2()
}
if ($("#drawing3").is(":within-viewport")) {
drawing3()
}
if ($("#drawing4").is(":within-viewport")) {
drawing4()
}
if ($("#drawing5").is(":within-viewport")) {
drawing5()
}
});
(我知道我应该将 DOM 元素放入变量中,但我计划在重构代码时这样做。)
我的第一个猜测是创建一个数组,但是.. 不知道如何在我的代码中使用它。(我是一个大初学者)