当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Basic var syntax: Variable already defined?

问题描述:

I have the following code, which tests if an element is present in the browser viewport:

(function ($) {

$.fn.visible = function (partial, hidden, direction) {

var $t = $(this).eq(0),

t = $t.get(0),

$w = $(window),

viewTop = $w.scrollTop(),

viewBottom = viewTop + $w.height(),

viewLeft = $w.scrollLeft(),

viewRight = viewLeft + $w.width(),

_top = $t.offset().top,

_bottom = _top + $t.height(),

_left = $t.offset().left,

_right = _left + $t.width(),

compareTop = partial === true ? _bottom : _top,

compareBottom = partial === true ? _top : _bottom,

compareLeft = partial === true ? _right : _left,

compareRight = partial === true ? _left : _right,

clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true,

direction = (direction) ? direction : 'both';

if (direction === 'both') return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));

else if (direction === 'vertical') return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));

else if (direction === 'horizontal') return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));

};

})(jQuery);

However, when I run this through JS lint, I get an error stating that direction is already defined. Where is my syntax wrong?

(The script still works)

网友答案:

direction is the parameter name and you are defining it inside the function with var direction.

If you change the comma of the previous line to a semicolon, i.e. make direction = ... not part of the var statement, you'll be fine.

网友答案:

Its because direction is already a paremeter to your function. And then in the var statement youre declaring it again. try:

[...]
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
direction = (direction) ? direction : 'both';
[...]

for example. (Changed the , to a ;) that will make the direction line a new assertion statement itsself without a var keyword.

b.t.w.

statements like your assertion to direction can be shortened like this:

direction = direction || 'both';

this will result in 'both' beeing assigned to direction if direction is undefined or any other falsy value.

分享给朋友:
您可能感兴趣的文章:
随机阅读: