【发布时间】:2017-02-23 17:49:36
【问题描述】:
我在将 DOM 元素传递给自定义插件中的函数时遇到问题。如您所见,我在$(window).scroll(); 函数中调用了eHeight(this);,我收到了这个错误:
未捕获的类型错误:无法读取未定义的属性“attr”
然后我将this 更改为eHeight(elem);,这次我收到了这个错误:
Uncaught ReferenceError: elem is not defined
如何将选定的元素传递给eHeight()?
(function($) {
$.fn.boxHeight = function(options) {
var settings = $.extend({
elemHeight: null
}, options);
var start = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > start) {
eHeight(this);
}
start = st;
});
function eHeight() {
var elem = $.trim(elem.attr('id'));
elem = "#" + elem;
var theHeight = $(elem).height();
if ($.isFunction(options.elemHeight)) {
options.elemHeight.call();
}
options.elemHeight.call();
}
};
})(jQuery);
$('#c').boxHeight({
elemHeight: function() {
$('#result').html('The Height is: ');
}
});
div {
height: 600px;
width: 100%;
}
#c {
background-color: khaki;
}
#result {
position: fixed;
right: 0;
top: 0;
background: yellow;
height: 40px;
width: 220px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='a'>A</div>
<div id='b'>B</div>
<div id='c'>C</div>
<div id='d'>D</div>
<div id='e'>E</div>
<div id='f'>F</div>
<div id='result'></div>
【问题讨论】:
-
那句话
var elem = $.trim(elem.attr('id'));毫无意义:) -
elem在哪里定义?eHeight不需要参数。 -
@guest271314,如您所见,我试图在
eHeigh()函数中定义它。我也尝试在设置之前在插件之上定义它,但仍然遇到同样的错误 -
您是否希望
elem成为插件链接到的元素?
标签: javascript jquery