我对 JavaScript 很陌生。我正在尝试为某些元素设置相等的高度。除了将函数移到“addEvent”声明之外,我设法做了所有事情。
换句话说,这段代码有效:
window.addEvent('domready', function() {
var elements = $$( 'div#leftcolumn div.module_menu' );
if( elements && elements.length > 1 ) {
var heights = [];
elements.each( function( el ) {
heights.push( el.getStyle('height').toInt() );
});
maxHeight = Math.max.apply( Math, heights ) + "px";
elements.each( function( el ) {
el.setStyle('height', maxHeight );
});
delete(heights);
}
}
);
虽然此代码不起作用:
function matchHeight( selector ) {
var elements = $$( selector );
if( elements && elements.length > 1 ) {
var heights = [];
elements.each( function( el ) {
heights.push( el.getStyle('height').toInt() );
});
maxHeight = Math.max.apply( Math, heights ) + "px";
elements.each( function( el ) {
el.setStyle('height', maxHeight );
});
delete(heights);
}
}
window.addEvent( 'domready', matchHeight( 'div#leftcolumn div.module_menu' ) );
我已经用更简单的功能进行了测试,它可以工作,例如:
window.addEvent('domready', function() { alert('test'); } )
相当于
function giveMessage() { alert('test'); }
window.addEvent( 'domready', giveMessage())
这是为什么?