【发布时间】:2017-08-29 17:46:06
【问题描述】:
下面的add8函数里面有很多for循环。出于这个问题的目的,我已经截断了它,但是我的源代码中的原始函数中有更多的循环。看看:
function select( selector ){
return document.querySelectorAll( selector );
}
function add8(){
var x = select( '[ x ]' ), y = select( '[ y ]' ),
x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
i = 0,
val = 0;
for( i = 0; i < x.length; i++ ){
val = x[ i ].getAttribute( 'x' );
val = Number( val ) + 8;
x[ i ].setAttribute( 'x', val );
}
for( i = 0; i < y.length; i++ ){
val = y[ i ].getAttribute( 'y' );
val = Number( val ) + 8;
y[ i ].setAttribute( 'y', val );
}
for( i = 0; i < x1.length; i++ ){
val = x1[ i ].getAttribute( 'x1' );
val = Number( val ) + 8;
x1[ i ].setAttribute( 'x1', val );
}
for( i = 0; i < y1.length; i++ ){
val = y1[ i ].getAttribute( 'y1' );
val = Number( val ) + 8;
y1[ i ].setAttribute( 'y1', val );
}
// Alot more 'for' loops follow...
}
add8();
您可能会注意到在这些 for 循环中只需要更改几个值,因此我迫切需要一个可以重用大量代码同时使整体代码更短更简洁的函数。
类似
function dynamicFunc( dynamicVar, dynamicStr ) {
for( i = 0; i < dynamicVar.length; i++ ){
val = dynamicVar[ i ].getAttribute( dynamicStr );
val = Number( val ) + 8;
dynamicVar[ i ].setAttribute( dynamicStr, val );
}
}
function add8(){
var x = select( '[ x ]' ), y = select( '[ y ]' ),
x1 = select( '[ x1 ]' ), y1 = select( '[ y1 ]' ),
x2 = select( '[ x2 ]' ), y2 = select( '[ y2 ]' ),
cx = select( '[ cx ]' ), cy = select( '[ cy ]' ),
i = 0,
val = 0;
dynamicFunc( x, 'x' );
dynamicFunc( y, 'y' );
dynamicFunc( x1, 'x1' );
dynamicFunc( y1, 'y1' );
// Alot more follow...
}
add8();
自动化那些for 循环,但下面的示例似乎不起作用。我还不太擅长 JS,我想我需要一点帮助。我怎样才能做到这一点?谢谢。
注意:我在源代码中处理了很多 SVG,因此在我的 JavaScript 中选择了属性 x、y、x1 等。
额外说明:我在这里使用的是香草 JS。
【问题讨论】:
标签: javascript function variables for-loop automation