我有一个简单的问题。如果该函数具有调整大小功能,为什么该函数返回仅第一个元素宽度的两倍?
var $element1 = $( '.one' ),
$element2 = $( '.two' );
function Width( element ) {
$( window ).resize(function() {
var width = element.width();
console.log( width );
});
$( window ).resize();
}
Width( $element1 );
Width( $element2 );
我的代码有问题吗?
fiddle http://jsfiddle.net/eLLcZ/
没有调整大小功能的 fiddle http://jsfiddle.net/VbX8L/
最佳答案
使用$( window ).resize();
Width()
内将调用所有 window
累计resize
每次处理程序:
Width( $element1 ); // the `window` has 1 `resize` handler, it's invoked
// log: 100
Width( $element2 ); // the `window` has 2 `resize` handlers, both are invoked
// calling the 1st handler a 2nd time (totaling 3 logs)
// log: 100
// log: 150
如果您有其他元素(例如 $element3
at 200px
),此扩展将继续:
Width( $element3 ); // Adds a 3rd handler, invokes the 1st and 2nd again
// log: 100
// log: 150
// log: 200
<小时/>
要仅调用当前处理程序,至少在它绑定(bind)到事件时,您需要直接调用它,而不是每次都触发整个事件:
function Width( element ) {
function onResize() {
var width = element.width();
console.log( width );
}
$( window ).resize(onResize); // add for later
onResize(); // call once now
}
Width( $element1 ); // log: 100
Width( $element2 ); // log: 150
您仍然可以稍后触发整个事件以一次运行所有处理程序:
$( window ).resize(); // log: 100
// log: 150
关于javascript - 为什么这个函数返回两倍的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098580/